14

In the documentation of ASP.NET MVC says that you should do something like this when have a link in a view

<a href="@href("~/SubPage")">Subpage</a>.

The razor engine replaces @href("~/SubPage")to /Subpage.

What is the advantage of do it this way instead

<a href="/SubPage">Subpage</a>.

In cases like this and in others (like creating a form) why use the razor engine instead of write directly what you want. I think is faster on the server side to print something directly that let the engine to generate it.

Ricardo Polo Jaramillo
  • 12,110
  • 13
  • 58
  • 83

3 Answers3

24

If your application runs in a subfolder, the Razor @href will create the correct link like this:

www.myapp.com/subfolder/SubPage

If you write it by yourself your link will be like this and will not work:

www.myapp.com/SubPage

Thats because ~ will be replaced with your application root by Razor.

Marc
  • 6,749
  • 9
  • 47
  • 78
  • And if I write the link right with the subfolder or the app is not in a subfolder, is there any advantages? – Ricardo Polo Jaramillo Feb 23 '12 at 04:48
  • 6
    No, I don't think so. But you loose flexibility - you are never able to change the name of the subfolder without searching your whole project where you wrote down that name. I highly disadvise to do that. – Marc Feb 23 '12 at 04:59
  • 1
    +1- this little gem (@href) is SOO overlooked by many devs (when not using @Html.ActionLink()). would give you a double vote if i could :) – jim tollan Feb 23 '12 at 08:29
2

The ActionLink method cannot take HTML.

You need to make a normal <a> tag, and use @Url.Action(...) for the href.

<a href="@Url.Action("ActionName", "ControllerName")">Link Text</a>.
RajeshKdev
  • 6,365
  • 6
  • 58
  • 80
0

I simply write

<a href="SubPage">Subpage</a>

I can't realize any negative fallback

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • 1
    If you have defined custom routes, this would potentially break links. For example, if I have a custom route `a/b/c` mapped to the `SubPage` action of the `PageController` and my link href is `OtherPage`, the browser will navigate to `a/b/OtherPage` though, in this context, the intended target would likely be `Page/OtherPage`. This isn't just about how your app is currently written, it's about writing every app in a way that is adaptive and can degrade gracefully. This makes the app a bit more portable and also more readily supports future changes. – defines Jul 10 '13 at 20:15