4

I am struggling with MVC - which I love - and it's features. I am trying to load a menu in the Application_Start event. I want to load some links with the correct url (controllerName/actionName) but I can't use the Url.Action or other methods to build the path.

Can anybody help me?

LeftyX
  • 35,328
  • 21
  • 132
  • 193

2 Answers2

5
protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);

    var context = new HttpContextWrapper(HttpContext.Current);
    var routeData = RouteTable.Routes.GetRouteData(context) ?? new RouteData();
    var requestContext = new RequestContext(context, routeData);
    var urlHelper = new UrlHelper(requestContext);
    var url = urlHelper.Action("Home", "Index");
    // TODO: do something with the url
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 2
    note: fails in integrated mode : http://blogs.iis.net/mvolo/archive/2007/11/10/Request-is-not-available-in-this-context-exception-in-Application_5F00_Start.aspx – Simon_Weaver Jan 29 '13 at 21:40
5

Why would you want to build your menu in the application_start? Is it for some kind of caching? Anyway here goes..

RegisterRoutes(RouteTable.Routes);
var httpContext = new HttpContextWrapper(HttpContext.Current);
UrlHelper urlHelper = new UrlHelper( new RequestContext(httpContext, new RouteData()));
var urlToHome = urlHelper.RouteUrl("Home");

I would rather recommend doing a RenderAction on your masterpage what points to a action that is cached, or something like that.

Johan Wikström
  • 921
  • 8
  • 18
  • 2
    note: fails in integrated mode : http://blogs.iis.net/mvolo/archive/2007/11/10/Request-is-not-available-in-this-context-exception-in-Application_5F00_Start.aspx – Simon_Weaver Jan 29 '13 at 21:41