Referencing JavaScript in ASP.NET MVC Master Pages

Here's a quick tip on including JavaScript files in your MVC master page views.  First off, put your .js file in the Content folder (or a sub-folder of it).  This folder is available directly over the web.  Next you need to reference the file in your master page.  In the head element use the following:

<script src="Content/js/jquery-1.2.3.min.js" type="text/javascript"></script>

But wait!  there's a problem with this.  Depending on what route has led to your view, the directory may be incorrect.  For example, "http://mymvcsite.com/about" will find the js just fine since the Content folder is a sibling folder to the about folder.  However, if your route was "http://mymvcsite.com/about/someaction", the script reference in your page will be looking for the file here: "http://mymvcsite.com/about/Content/jquery-1.2.3.min.js" and so your js won't work.  This problem doesn't seem to happen for css files.  The MVC rewrites the href to point to the correct place.

There is a simple fix though.  Instead of specifying the js file directly, use the Url.Content() function.  For example:

<script src="<%= Url.Content("~/Content/js/jquery-1.2.3.min.js") %>" type="text/javascript"></script>

Also note that the "~" will work in link elements to reference css, but not in script elements referencing JavaScript.  It would be nice if this is fixed in the next CTP.