简体   繁体   English

MVC5 Url.Action在区域内返回null

[英]MVC5 Url.Action returns null inside area

We have a MVC application with different areas. 我们有一个不同领域的MVC应用程序。 At moment just one area is registered (defined in config) and no route registrations is done in area registration. 目前,只有一个区域被注册(在config中定义),区域注册中没有路由注册。 I have run into issues with routing as Url.Action method stopped to work. 由于Url.Action方法停止工作,我遇到了路由问题。 My simplified RouteConfig looks like this: 我简化的RouteConfig看起来像这样:

        routes.MapRoute(
            name: "Second",
            url: "second/{action}/{id}",
            defaults: new { controller = "Second", action = "Action", id = UrlParameter.Optional },
            namespaces: new[] { "MvcApplication1.Areas.MyArea.Controllers" }
        ).DataTokens["area"] = "MyArea";


        routes.MapRoute(
            name: "Home",
            url: "home/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "MvcApplication1.Controllers" }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "MvcApplication1.Controllers" }
        );

The problem is that when I try to call @Url.Action("Index", "Home") inside Action.cshtml in Second controller in MyArea it returns null. 问题是,当我尝试在MyArea的Second控制器中的Action.cshtml中调用@Url.Action("Index", "Home") ,它返回null。 When I call the same in Index.cshtml in Home controller it works well. 当我在Home控制器的Index.cshtml中调用相同的控件时,效果很好。 I have found out that when I use @Url.Action("Index", "Home", new {Area = ""}) in Action.cshtml it works well too, but why this is happening? 我发现在@Url.Action("Index", "Home", new {Area = ""})使用@Url.Action("Index", "Home", new {Area = ""}) ,它也能很好地工作,但是为什么会这样呢? How can I avoid that to be able to call just @Url.Action("Index", "Home") without route values? 如何避免只调用@Url.Action("Index", "Home")而没有路由值的情况?

This is not a problem but it's actually the proper behavior. 这不是问题,但实际上是正确的行为。

When you use @Url.Action() or @Html.ActionLink it will by default use the area from where it's being called. 当您使用@ Url.Action()或@ Html.ActionLink时,默认情况下它将使用被调用的区域。 If you want to link to a different area, as in this case, you need to specify the parameter area as you already found out. 如果要链接到其他区域,在这种情况下,需要指定已经发现的参数区域。

In this particular case when you're trying to link to root area you need to specify the parameter as an empty string as you did. 在这种特殊情况下,当您尝试链接到根区域时,需要像以前一样将参数指定为空字符串。 ({Area=""}) ({Area =“”})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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