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?
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With