When building EPiServer websites with ASP.NET MVC the LinkURL property doesn't do us much good. Here's a couple of MVC-compatible ways for getting the URL for a page.
Pretty much since the dawn of time, or at least since the Finnish heavy metal band Lordi won the Eurovision Song Contest with the song Hard Rock Hallelujah, we have been able to get URL for a page in EPiServer CMS using the LinkURL property on the PageData objects. With EPiServer 7 that changes. Although the LinkURL property still exists and hasn’t changed the recommended approach now is to use routing.
When using Web Forms the LinkURL property still produces the expected result, but when used in an ASP.NET MVC view it will be outputted as the internal URL (/link/some_weird_guid.aspx?id=42… etc). Luckily EPiServer provides a couple of ways to get the URL for a page when building sites with MVC.
One way of getting the URL for a page when using MVC is to use an extension method for the UrlHelper class named PageUrl. This method resides in a class in the EPiServer.Web.Mvc.Html namespace and has a single parameter of type string named classicalUrl. Feed it the LinkURL property of a PageData object and the relative URL for the page is returned. In a view it may look like this:
@model MySite.Models.Pages.StandardPage @Url.PageUrl(Model.LinkURL)
The PageUrl extension method is nice and simple but in some cases we don’t have access to an UrlHelper instance. In other cases we may want to control what language version of the page we want the URL to be to. Or, we may want the URL for a different action than Index. In those cases we can use the UrlResolver class which is located in the EPiServer.Web.Routing namespace.
The UrlResolver class has a method named GetVirtualPath with two overloads. In it’s simplest form it requires a single argument, a ContentReference. Other overloads allow us to pass it a language and/or additional route values and a RequestContext. Get a hold of an instance of UrlResolver and invoke the method with a ContentReference and, just like with the PageUrl method, the relative URL for the page is returned.
//using EPiServer.Web.Routing; var urlResolver = ServiceLocator.Current.GetInstance<UrlResolver>(); var pageUrl = urlResolver.GetVirtualPath(currentPage.ContentLink);