Five common mistakes for ASP.NET MVC accesing resources : css, js, images, ajax
This is a Razor /MVC5 variant of older post
http://msprogrammer.serviciipeweb.ro/2010/10/09/five-common-mistakes-for-asp-net-mvc-accesing-resources-css-js-images-ajax/
To have once for all the link to show to people, because too much makes the same error again and again. (From here – you can use ResolveUrl or Url.Content – it’s the same for me. I use ResolveUrl because I used first …)
Case 1 The image does not display
Please check you have the following :
1 | <img src= "@Url.Content(" ~/Content/images/YOURIMAGE.jpg " )" alt= "image" style= "border:0" /> or |
1 | <img src= "~/Content/images/YOURIMAGE.jpg" alt= "image" style= "border:0" /> |
Case 2 The css does not show
Please check you have the following :
1 | @ string .Format( "<link href=" {0} " type=" text/css " rel=" stylesheet " />" , Url.Content( "~/Content/your.css" )) |
or
1 2 3 4 | <style type= "text/css" > @ import '@Url.Content("~/Content/your.css")' ; </style> |
1 2 3 4 | <style type= "text/css" > <link href= '~/Content/your.css' type= 'text/css' rel= 'stylesheet' /> </style> |
Case 3 The js does not execute (undefined error)
3.1 Please check you have the following :
1 | <script type= "text/javascript" src= "@Url.Content(" ~/Scripts/yourjs.js ")" ></script> |
or
1 | <script type= "text/javascript" src= "~/Scripts/yourjs.js" ></script> |
This should be either in _Layout.cshtml, or in the scripts section
1 | @section scripts { } |
in your .cshtml file.
3.2 please check in browser console ( press F12 ) for any javascript error that code may have
Case 4 The js does execute in .cshtml page, but did not execute under js file
Please check you DO NOT have the following @something in the js file. The js file is not interpreted by the same engine as cshtml, so can not interpret asp.net tags. Instead , add a parameter to your function for each @ variable that you have. Simple example : Let’s say in cshtml you have :
1 2 3 4 5 6 7 8 | <script type=”text/javascript”> function Generate(){ window.open('@Url.Action(“About”)’); } </script> |
and you call Generate() from .cshtml file. Now you want the same in a .js file. The function Generate will have a parameter instead of Razor variable
1 | function Generate(url){ window.open(url); } |
and call like this from .cshtml file:
1 | Generate( '@Url.Action("About")' ); |
Case 5 The ajax request gives you a 404 error.
Please ensure that you have
1 | @Url.Content("~/path”) |
and not
1 | /path |
when you call the Ajax URL
Bonus 1: T4MVC , http://mvccontrib.codeplex.com/releases
Bonus 2: Edit the project file and put <MvcBuildViews>true</MvcBuildViews>
( short url: http://bit.ly/asp5Mistakes)