我遇到从区域视图到非区域视图的反向链接问题。
Web应用程序树:
默认路线配置:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
name: "Localization",
url: "{culture}/{controller}/{action}/{id}",
defaults: new { culture = "de-DE", area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
区域路线配置:
public class Area1AreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Area1";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Photovoltaics_localized",
"{culture}/Photovoltaics/{controller}/{action}/{id}",
new { culture = "de-DE", action = "Index", id = UrlParameter.Optional }
);
context.MapRoute(
"Area1_default",
"Area1/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
注册路线配置(Global.asax.cs)
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
[..]
当我进入基本视图(/ Views / Base / Index.cshtml )时,代码@Html.ActionLink("My home link", "Index", "Home")
会生成我期望的链接http://localhost:81/de-DE/Home。
当我进入区域视图(/ Areas / Area1 / Views / Setting / Index.cshtml )时,相同的代码会生成链接http://localhost:81/de-DE/Area1/Home,但这指向无处。 / p>
我了解到代码@Html.ActionLink("My home link", "Index", "Home", new { area = ""}, null)
适用于区域和非区域视图,并且会导致http://localhost:81/de-DE/Home视图正确。
如何以调用链接创建方法的方式构建我的路由配置,没有区域作为参数始终链接到基本视图/控制器?
或者有更好的解决方案来实现这一目标吗?
我的期望是:
@Html.ActionLink("My home link", *action*, "controller")
= http://localhost:81/de-DE/ 行动
@Html.ActionLink("My home link", *action*, *controller*, new { area = *area*}, null)
= http://localhost:81/de-DE/ 区域 / 行动
答案 0 :(得分:1)
这与路由无关。这是ActionLink方法URL创建的默认行为。您可以在以下代码中看到这一点(取自ASP.NET MVC代码集):
if (values != null)
{
object targetAreaRawValue;
if (values.TryGetValue("area", out targetAreaRawValue))
{
targetArea = targetAreaRawValue as string;
}
else
{
// set target area to current area
if (requestContext != null)
{
targetArea = AreaHelpers.GetAreaName(requestContext.RouteData);
}
}
}
正如您所看到的,如果您没有为区域传递值,则会占用您当前所在的区域。
我能想到的唯一解决方案是创建自己的HTML扩展。类似的东西:
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName)
{
return htmlHelper.ActionLink(linkText, actionName, controllerName, new { area = String.Empty });
}