23

Can someone please explain why I should use (or should I?):

<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>

vs

 <script type="text/javascript" src="/Scripts/SomeScript.js"></script>

Thanks

raklos
  • 28,027
  • 60
  • 183
  • 301

1 Answers1

32

The fragment @Url.Content("/Scripts/SomeScript.js") does absolutely nothing, and is equivalent to just /Scripts/SomeScript.js.

However, for paths starting with "~", it will translate the url to the correct, application relative url, e.g., @Url.Content("~/Scripts/SomeScript.js") could translate to /MyVirtualDirectory/Scripts/SomeScript.js, if you deployed your web application to a virtual directory MyVirtualDirectory below the root folder of the web site.

Ruben
  • 15,217
  • 2
  • 35
  • 45
  • 1
    +1, With other words: `Url.Content` makes sure that all links works no matter if the site is in a virtual directory or in the web site root. – jgauffin Mar 01 '12 at 12:33
  • 17
    Just an additional note: `Url.Content` it's been a great help so far, but in MVC4/Razor2.0 it's no longer needed, we can now use: `src="~/Scripts/SomeScript.js"`. – Cristian Lupascu Mar 01 '12 at 13:07
  • Also, because the default `type` is `text/javascript` it's OK to leave it out. This is OK for all current, and even old, browsers. – Aaron Aug 29 '14 at 06:02