Correct way to reference Javascript in ASP.NET MVC?

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?

EDIT: This is obviously a very old question at this point, but I’m editing to mention that in MVC4, all you need is this:

src="~/Scripts/Whatever.js"

That’s enough for Razor to figure out where you mean, using the root path.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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>

Method 3

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.

Method 4

I myself use mvccontrib htmlhelpers for this at the moment.

This can be useful too.

Method 5

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>rn",
                         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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x