MVC5 Url.Action returns null inside area

匿名 (未验证) 提交于 2019-12-03 01:26:01

问题:

We have a MVC application with different areas. At moment just one area is registered (defined in config) and no route registrations is done in area registration. I have run into issues with routing as Url.Action method stopped to work. My simplified RouteConfig looks like this:

        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. When I call the same in Index.cshtml in Home controller it works well. 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? How can I avoid that to be able to call just @Url.Action("Index", "Home") without route values?

回答1:

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. 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=""})



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!