Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Application_Start and Url.Action

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?

like image 731
LeftyX Avatar asked Dec 29 '22 09:12

LeftyX


2 Answers

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.

like image 190
Johan Wikström Avatar answered Jan 03 '23 16:01

Johan Wikström


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
}
like image 45
Darin Dimitrov Avatar answered Jan 03 '23 18:01

Darin Dimitrov