Search code examples
c#htmlasp.netrazorrazor-2

Relative links with Razor in ASP.NET without MVC


We're working on a site that was set up with all the pages in the root directory. As a result all the links are referencing locations in the same directory they're located in by default...

<a href="Page.cshtml">Page</a> 

We've restructured it and some of the pages are now in sub folders, so the links throughout the site now need to be relative. I've read that a tilde (~) won't work in the markup when using Razor. ie <a href="~/Page.cshtml">Page</a>

How can a link be formatted so that it points to something in the root directory?

Something like? <a href="@Href("~/Page.cshtml")">Page</a>

EDIT: Resolved with: <a href="@Href("~/")Page.cshtml">Page</a>


Solution

  • Try this:

    @helper _href(string url)
    {
        @VirtualPathUtility.ToAbsolute(url)
    }
    

    To use it on a page:

    <a href="@_href("~/page.html")">linky</a>

    Edit: How I never knew about the built-in Href method is beyond me. You should definitely use that instead.