asp.netjavascriptasp.net-mvc

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.


Solution

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