tags:

views:

60

answers:

1

First we have the form:

<link href="../../../content/somecontent" />

This is annoying to figure out (need to count path depth one by one) and the most prone to mistakes. Someone came up with this:

<link runat="server" href="~/content/somecontent" />

This is easier but I don't know how casual I can be using that solution. Can it be used anywhere? Does it work with Spark? How does it affect rendering speed? And the last and worst resort would be:

<link href="/content/somecontent" />

This doesn't allow the web app to reside in a sub directory which I don't like, especially for testing purposes. Are there other, better ways that I'm not aware of?

+7  A: 

You can use

<link href="<%= Url.Content("~/Content/somecontent") %>" />

to point to some file. Using relative locations (your first example) won't work all the time because of the way routing can change depending on the current URL. In most of my projects, I use URL helpers to do this kind of thing.

public static class ExtensionsOfUrlHelper
{
    // TODO: Prepare for .NET 4.0, this will return MvcHtmlString
    public static string Asset(this UrlHelper url, string asset)
    {
        var path = "~/assets/" + asset;
        return string.Format("<link href=\"{0}\" />", url.Content(path));
    }
}

This keeps the view lighter, and I can just type...

<%= Url.Asset("some_asset") %>

... and be done with it.

When .NET 4.0 comes out, and you update your code base, you'll change your static to return a shiny new MvcHtmlString. This will happily prevent and double-escaping. (And you'll want to do this in any code that writes out HTML.)

Jarrett Meyer
Good advice. I didn't know of Url.Content() helper. I'll wait a bit more to keep answers coming, thanks.
ssg
Don't forget about the other HTML helpers such as ActionLink(), etc.
GalacticCowboy