0

I was wondering how to get a URL given the area, controller and action names. So far all I have managed to come up with is:

var httpContext = new HttpContextWrapper(HttpContext.Current);
var routeData = RouteTable.Routes.GetRouteData(httpContext);

if (routeData != null) {
    var virtualPath = routeData.Route.GetVirtualPath(new RequestContext(httpContext, routeData), new RouteValueDictionary(new { area = "Pages", controller = "Home", action = "Index" }));

    if (virtualPath != null) 
        newNode.Url = "~/" + virtualPath.VirtualPath;
}

However it does not work. I was wondering if someone could help.

Thanks

nfplee
  • 7,643
  • 12
  • 63
  • 124
  • Where do you need to do this? Do you have access to an HTTP Context? When you say that it doesn't work could you be a little more specific and explain the expected result and the actual result? – Darin Dimitrov Dec 02 '11 at 08:07
  • Thanks for your reply. I'm trying to add it to an MVC SiteMap provider i found online. The one i found lacked area support so i figured i'd simply add that to the route value dictionary but that is not the case as the wrong route gets selected. I have a feeling it's something to do with the data tokens. – nfplee Dec 02 '11 at 09:07

1 Answers1

2

Incase anyone is wondering, here's the solution I have come up with:

// Set the context
var context = new RequestContext(new HttpContextWrapper(HttpContext.Current),
    new RouteData());
var urlHelper = new UrlHelper(context);

// Set the url
var url = urlHelper.Action("Index", "Home",
    new RouteValueDictionary(new { area = "Pages" }));

I hope this helps someone.

nfplee
  • 7,643
  • 12
  • 63
  • 124