ASP.NET MVC Relative Paths

In my applications, I often have to use relative paths. For example, when I reference JQuery, I usually do so like this:

<script type="text/javascript" src="../Scripts/jquery-1.2.6.js"></script>

Now that I'm making the transition to MVC, I need to account for the different paths a page might have, relative to the root. This was of course an issue with URL rewriting in the past, but I managed to work around it by using consistent paths.

I'm aware that the standard solution is to use absolute paths such as:

<script type="text/javascript" src="/Scripts/jquery-1.2.6.js"></script>

but this will not work for me as during the development cycle, I have to deploy to a test machine on which the app will run in a virtual directory. Root relative paths don't work when the root changes. Also, for maintenance reasons, I cannot simply change out all the paths for the duration of deploying the test - that would be a nightmare in itself.

So what's the best solution?

Edit:

Since this question is still receiving views and answers, I thought it might be prudent to update it to note that as of Razor V2, support for root-relative urls is baked in, so you can use

<img src="~/Content/MyImage.jpg">

without any server-side syntax, and the view engine automatically replaces ~/ with whatever the current site root is.


Try this:

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

Or use MvcContrib and do this:

<%=Html.ScriptInclude("~/Content/Script/jquery.1.2.6.js")%>

While an old post, new readers should know that Razor 2 and later (default in MVC4+) completely resolves this problem.

Old MVC3 with Razor 1:

<a href="@Url.Content("~/Home")">Application home page</a>

New MVC4 with Razor 2 and later:

<a href="~/Home">Application home page</a>

No awkward Razor function-like syntax. No non-standard markup tags.

Prefixing a path in any HTML attributes with a tilde ('~') tells Razor 2 to "just make it work" by substituting the correct path. It's great.