views:

187

answers:

2

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?

A: 

Use the UrlHelper class: http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.aspx

You should be able to use it via the Url object in your controller. To map to an action, use the Action method: Url.Action("actionName","controllerName");. A full list of overloads for the Action method is here: http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.action.aspx

so your code would look like this:

        List<string> urlList = new List<string>();
        urlList.Add(Url.Action("Edit", "Help"));
        urlList.Add(Url.Action("Create", "Help"));
        urlList.Add(Url.Action("Company", "About"));
        urlList.Add(Url.Action("Management", "About"));

EDIT: It seems, from your new answer, that your trying to build a sitemap.

Have a look at this Codeplex project: http://mvcsitemap.codeplex.com/. I haven't used it myself, but it looks pretty solid.

Alastair Pitts
A: 

How about this (in the controller):

    public IEnumerable<SiteMapEntry> SiteMapEntries
    {
        get
        {
            var entries = new List<SiteMapEntry>();

            foreach (var route in this.Routes)
            {
                entries.Add(new SiteMapEntry
                (
                    this.Url.RouteUrl(route.Defaults),
                    SiteMapEntry.ChangeFrequency.Weekly,
                    DateTime.Now,
                    1F));
            }

            return entries;
        }
    }

Where the controller has member:

public IEnumerable<Route> Routes

Take note of:

this.Url.RouteUrl(route.Defaults)
JamesBrownIsDead
Just as an aside. It's recommended that you actually edit your original question rather than post a new answer (Unless it's the actual answer)
Alastair Pitts