views:

363

answers:

2

Hello everyone,

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?

Regards

Alberto

+1  A: 
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
+2  A: 

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
Yes, I want to do some caching. Thanks. It works.
vandalo
If it works please mark it as a accepted answer. Its how stackoverflow works! :)
Johan Wikström