简体   繁体   中英

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??

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:)

为了使用@Url.Action 扩展方法,您需要为 routeValues 参数指定 httproute 名称,如下所示:

@Url.Action("Index","Home", new { httproute ="AccessControlApi_default"} )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM