Correct way to reference Javascript in ASP.NET MVC?

前端 未结 5 1592
孤城傲影
孤城傲影 2020-12-29 07:27

What is the correct way to reference Javascript in ASP.NET MVC? Using something like ../../Scripts/Myscript.js seems to work fine for routes that are the traditional {contro

相关标签:
5条回答
  • 2020-12-29 07:34

    I've created my own HtmlHelper extensions that look like:

    public static string MEScriptBlock(this HtmlHelper html, string path, string releasePath)
    {
    #if DEBUG
    #else
        if (!string.IsNullOrEmpty(releasePath))
            path = releasePath;
    #endif
    
        return string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>\r\n",
                             path);
    }
    

    If intellisense is what you're after you could trick VS into thinking that a JS file has been loaded... E.g.

    <% if (false)
       { %>
        <script src="../../Scripts/Myscript.js" type="text/javascript"></script>
    <% } %>
    

    HTHs, Charles

    0 讨论(0)
  • 2020-12-29 07:49

    In case anyone else finds this answer that is using MVC Razor, here's the syntax for that:

    <script type="text/javascript" src="@Url.Content("/Scripts/MyScript.js")"></script>
    
    0 讨论(0)
  • 2020-12-29 07:50

    I myself use mvccontrib htmlhelpers for this at the moment.

    This can be useful too.

    0 讨论(0)
  • 2020-12-29 07:51

    I also reference js the same way as CMerat:

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

    If you need Intellisense for jquery, you can find instructions on how to set it up here. As far as i know, you cant get Intellisense for any custom js file you reference - you will need to create the Intellisense file for it first.

    0 讨论(0)
  • 2020-12-29 07:52

    <script src="<%= Url.Content("~/Scripts/Myscript.js") %>" type="text/javascript"></script>

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