ASP.NET MVC: Route to URL

Posted by JamesBrownIsDead on Stack Overflow See other posts from Stack Overflow or by JamesBrownIsDead
Published on 2010-05-11T04:29:22Z Indexed on 2010/05/11 4:34 UTC
Read the original article Hit count: 268

Filed under:
|

What's the easiest way to get the URL (relative or absolute) to a Route in MVC? I saw this code here on SO but it seems a little verbose and doesn't enumerate the RouteTable.

Example:

List<string> urlList = new List<string>();
urlList.Add(GetUrl(new { controller = "Help", action = "Edit" }));
urlList.Add(GetUrl(new { controller = "Help", action = "Create" }));
urlList.Add(GetUrl(new { controller = "About", action = "Company" }));
urlList.Add(GetUrl(new { controller = "About", action = "Management" }));

With:

protected string GetUrl(object routeValues)
{
    RouteValueDictionary values = new RouteValueDictionary(routeValues);
    RequestContext context = new RequestContext(HttpContext, RouteData);

    string url = RouteTable.Routes.GetVirtualPath(context, values).VirtualPath;

    return new Uri(Request.Url, url).AbsoluteUri;
}

What's a better way to examine the RouteTable and get a URL for a given controller and action?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about route