February 4, 2016 20:38 by
Peter
I have been operating with ASP.NET MVC for some time and yet I still had trouble making an attempt to get a URL in a view. URL generation is particularly important for ASP.NET MVC as a result of 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 2 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 - thus 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 a similar result additional 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.
HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.