Search code examples
c#asp.netasp.net-mvcasp.net-mvc-routingasp.net-mvc-areas

Generating URLs for ASP.NET MVC Area routing with subfolder


I have an ASP.NET MVC app which has areas with special routes as following:

Area registration file:

context.Routes.MapHttpRoute(
    "AccessControlApi_default",
    "accesscontrol/api/{controller}/{id}",
    new { id = RouteParameter.Optional }
    );

context.MapRoute(
    "AccessControl_dashboardwidgets",
    "accesscontrol/dashboardwidgets/{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional },
    new[] { "AccessControl.Controllers.DashboardWidgets" }
);

context.MapRoute(
    "AccessControl_default",
    "accesscontrol/{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional },
    new[] { "AccessControl.Controllers" }
);

First routing is for api, second is for controllers and views in a sub-folder under the area, and third is for the default controllers under area.

Everything is working well with routing, but the issue is with the use of Url.Action like this one:

<a href='@Url.Action("Index","Home",new{area="AccessControl"})'>Go to home</a>

It's always injecting dashboardwidgets keyword in the url between area and controller like this: {host}/accesscontrol/dashboardwidgets/Home/Index

How can I generate urls according to my needs, either to root of area, or to this sub folder under the area??


Solution

  • I think the solution would be to use named routes in constructing your links. You would need to switch the call from

    @Url.Action("Index","Home",new{area="AccessControl"})
    

    to

    @Url.RouteUrl("AccessControl_dashboardwidgets", new {area = "AccessControl", controller="Home", action="Index"})
    

    or

    @Url.RouteUrl("AccessControl_default", new {area = "AccessControl", controller="Home", action="Index"})
    

    Depending on which route you are aiming for.

    Sorry about the confusion with the parameters, was editing while doing something else... multitasking on Monday morning is obviously to be avoided:)