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= '<%= ResolveUrl("~/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' />" , ResolveUrl( "~/Content/your.css" )) %> |
or
1 2 3 4 | <style type= "text/css" > @ import '<%= ResolveUrl("~/Content/your.css") %>' ; </style> |
Case 3 The js does not execute (undefined error)
Please check you have the following :
1 | <script type= "text/javascript" src= '<%= ResolveUrl("~/Scripts/yourjs.js")%>' ></script> |
Case 4 The js does execute in aspx page, but did not execute under js file
Please check you DO NOT have the following
<%
in the js file. The js file is not interpreted by the same engine as aspx, so can not interpret asp.net tags. Instead , add a parameter to your function : the path.
Simple example : Let’s say in aspx 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();
When you put in .js file, please put this :
1 2 3 4 | function Generate(url){ window.open(url); } |
and call like this :
1 | Generate( '<% Url.Action(“About”)%>' ); |
Case 5 The ajax request gives you a 404 error.
Please ensure that you have
1 | <%= ResolveUrl("~/path”)%> |
and not
/path
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)