I\'m fairly new to ASP.NET MVC, and I\'m having a little trouble with scripts... in particular, I want to use jQuery in most pages, so it makes sense to put it in the master
Based on the other replies, perhaps an extension method on Html (which is very common for MVC), similar to Eduardo's answer:
<%=Html.Script("~/Scripts/jquery-1.2.6.js")%>
With:
public static string Script(this HtmlHelper html, string path)
{
var filePath = VirtualPathUtility.ToAbsolute(path);
return "<script type=\"text/javascript\" src=\"" + filePath + "\"></script>";
}
ResolveUrl is the most elegant solution IMO. Though it's a real shame the urls to CSS are resolved by runat=server and not the script.
Our applications are deployed using virtual directories, and we have had some issues with other answers mentioned here (not resolving the path correctly). One way that worked well, (not the only way mind you), was to use this:
<script src="<%=Request.ApplicationPath%>/Web/AppName/JavaScript/jquery-1.4.1.js"></script>
I have a AppHelper class with some methods for adding script references:
public static string ReferenceScript(string scriptFile)
{
var filePath = VirtualPathUtility.ToAbsolute("~/Scripts/" + scriptFile);
return "<script type=\"text/javascript\" src=\"" + filePath + "\"></script>";
}
so in your master page you can use:
<%= AppHelper.ReferenceScript("jquery-1.2.6.js") %>
At work we are doing something like this from the ASP code behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Const jQuery As String = "jQuery"
With Me.Page.ClientScript
If Not .IsClientScriptIncludeRegistered(jQuery) Then
.RegisterClientScriptInclude(jQuery, VirtualPathUtility.ToAbsolute("~/Includes/jQuery-1.2.6.js"))
End If
End With
End Sub
I don't know if it's possible to do that with ASP.NET MVC.
You should take a look at using a utility like squish it. It can aggregate and obfuscate all of your css and js files for you. Or you can use it to generate script tags if you just keep it in debug more by using ForceDebug()
http://www.codethinked.com/squishit-the-friendly-aspnet-javascript-and-css-squisher