I have been working with ASP.NET MVC for some time and yet I still had trouble trying to generate a URL in a view. URL generation is particularly important for ASP.NET MVC because it uses a routing engine to map URLs to code. If we hard code a URL then we lose the ability to later vary our routing scheme.
I have found two ways that currently (ASP.NET MVC preview 2) work to generate URLs in a view. The first uses the GetVirtualPath method and seems overly complicated – so I wrapped it in a global helper:
public static string GenerateUrl(HttpContext context, RouteValueDictionary routeValues)
{
return RouteTable.Routes.GetVirtualPath(
new RequestContext(new HttpContextWrapper2(context), new RouteData()),
routeValues).ToString();
}
But then I found that I could achieve the same result more simply using UrlHelper, accessible via the Url property of the view.
// link to a controller
Url.Action("Home");
// link to an action
Url.Action("Home", "Index");
// link to an action and send parameters
Url.Action("Edit", "Product", new RouteValueDictionary(new { id = p.Id }));
Or, if you want the url for a hyperlink you can get that in one step using the ActionLink method on the Html property:
Html.ActionLink<HomeController>(c => c.Index(),"Home")
So I no longer see a need for my GenerateUrl method and have removed it from my helper. All of this would be much easier if there was some documentation. Im sure there is a better way so if you can think of an improvement please leave it in the comments.