views:

444

answers:

4

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 {controller}/{action}/{id}, but are more fragile for anything more or less complex than that. Of greater concern is that the rational absolute reference (/Scripts/Myscript.js) breaks Intellisense in Visual Studio.

How do you handle it?

+7  A: 

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

CMerat
I also do it this way.
Chad Moran
Does Intellisense work in VS this way?
Jeff Putz
+3  A: 

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.

cottsak
I'm aware of Scott's instructions, but what I'm getting from these responses are that there's no way to correctly reference the script *and* have Intellisense work for files that support it (like jQuery), other than using the ScriptManager.
Jeff Putz
That makes sense.. coz the auto-intellisense (if u want to call it that) is only away of script it can see in the page. As your script it 'linked' it is bound late and so the IDE is not aware of it's contents at design time.
cottsak
+1  A: 

I myself use mvccontrib htmlhelpers for this at the moment.

This can be useful too.

Arnis L.
A: 

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

Charlino