In my MVC application I have a default route defined:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new []{ "Demo.Controllers" }
);
I created a new Area called Admin and it added a route to in the AdminAreaRegistration class:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", controller = "Home", id = UrlParameter.Optional }
);
}
In my main _Layout file I tried to do the following:
@Html.RouteLink("Admin", "Admin_default")
It only works in certain cases (such as if I’m already in an Admin page). If I am in the /Home/About section of my site, then the URL gets generated like so:
/Admin/Home/About
If I am in my Index action of the Home controller (in the main area, not admin) then the URL gets generated like so:
/Admin
Why doesn’t RouteLink work like I think it should using Areas in MVC?
@Html.RouteLink("Admin", "Admin_default")this route uses the route with the name ofAdmin_defaultso it will always use that route to generate the url.@Html.RouteLink("Admin", "Admin_default", new { controller = "Home", action = "Index" })When you don’t specify stuff like route values most of MVC uses the values that currently exist. In this case since the
actionandcontrollervalues are null it looks at theRouteValuesand checks to see if they’re there and if they’re found they use the values found there instead.This is sometimes helpful. For instance if you want
{id}to be populated with the same value that was used on the page.Url:
/home/edit/1701@Html.RouteLink("Refresh", "Default")would result in the same exact url – you can specify overrides if you want.