Using scripts in a master page with ASP.NET MVC

前端 未结 11 1290
难免孤独
难免孤独 2020-11-28 19:06

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

相关标签:
11条回答
  • 2020-11-28 19:28

    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>";
    }
    
    0 讨论(0)
  • 2020-11-28 19:28

    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.

    0 讨论(0)
  • 2020-11-28 19:29

    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>
    
    0 讨论(0)
  • 2020-11-28 19:30

    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") %>
    
    0 讨论(0)
  • 2020-11-28 19:30

    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.

    0 讨论(0)
  • 2020-11-28 19:30

    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

    0 讨论(0)
提交回复
热议问题