MVC5 Url.Action在区域内返回null [英] MVC5 Url.Action returns null inside area

查看:96
本文介绍了MVC5 Url.Action在区域内返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个MVC应用程序,它具有不同的领域.目前,仅注册了一个区域(在config中定义),并且在区域注册中未进行任何路由注册.由于Url.Action方法停止工作,我遇到了路由问题.我简化的RouteConfig看起来像这样:

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" }
        );

问题是,当我尝试在MyArea的Second控制器中的Action.cshtml中调用 @ Url.Action("Index","Home")时,它返回null.当我在Home控制器的Index.cshtml中调用相同的控件时,它可以很好地工作.我发现在Action.cshtml中使用 @ Url.Action("Index","Home",新的{Area ="})时,它也能很好地工作,但是为什么会这样?如何避免只调用 @ Url.Action("Index","Home")而没有路由值的情况?

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?

推荐答案

这不是问题,但实际上是正确的行为.

This is not a problem but it's actually the proper behavior.

当您使用@ Url.Action()或@ Html.ActionLink时,默认情况下它将使用被调用的区域.在这种情况下,如果要链接到其他区域,则需要指定已经发现的参数区域.

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.

在这种特殊情况下,当您尝试链接到根区域时,需要像以前一样将参数指定为空字符串.({Area ="})

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

这篇关于MVC5 Url.Action在区域内返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆