Tuesday, October 5, 2010

ASP.MVC JS script source and CSS files not mapped correctly

I've meet a lot of questions regarding why CSS and JS attachments to an ASP.NET MVC page sometimes found in some page but not in other pages specially when you add a 4th segment to your url.

For example, your URL is
http://localhost/Home/Page/Article/1
Certainly, the CSS and javascripts files will not work correctly on this pages since ASP.NET MVC attached those files by default like this.
<script type="text/javascript" language="javascript" src="../../Scripts/jquery-1.4.1.js"></script>
Where it is mapped 2 levels higher of the Scripts folder. So when the parser looks for the included js script from the stated url it will look 2 levels higher only of the last segment which is 1. But your Url has 4 levels or segments which the parser ends up looking at the /Home segment and the actual JS file is in the root of your URL.

My solution for this is to create a base url instead of mapping it with ../../ I would create a helper that will generate a link tag or script tag for my CSS and my javascripts

Helper.cs
public static string GenerateCSSLink(this HtmlHelper helper, string cssPath)

      var request = helper.ViewContext.RequestContext.HttpContext.Request;
      string baseUrl = request.Url.Scheme + "://" + request.Url.Host + (request.Url.Port == 80 ? "" : ":" + request.Url.Port.ToString()) + "/";
      string url;
      if (cssPath.StartsWith("/"))
      {
          url = baseUrl + cssPath.Substring(1);
      }
      else
      {
          url = baseUrl + cssPath;
      }
      string link = "<link href=\"" + url + "\" rel=\"stylesheet\" type=\"text/css\" />";

      return link; 
}

In my Master page where I have included my CSS and Scripts I will import the namespace of my Helper.cs and I can now call
<%=Html.GenerateCSSLink("/Content/Site.css") %>

No comments:

Post a Comment