带有区域的 MVC -- Html.ActionLink 返回错误的 URL/路由? [英] MVC with Areas -- Html.ActionLink returning wrong URL/Route?

查看:31
本文介绍了带有区域的 MVC -- Html.ActionLink 返回错误的 URL/路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MVC3 并且在我的应用程序中有区域.一般来说,一切正常,我可以像这样导航到我的区域(例如 Admin=Area,Controller=Department):

I am using MVC3 and have Areas in my application. In general, everything works fine, I can navigate to my area (e.g. Admin=Area, Controller=Department) like this:

<%: Html.ActionLink("Departments", "DepartmentIndex", "Department", new { area = "Admin"}, null )%>

但是,我注意到如果我没有在 ActionLink 中指定区域,例如

However, what I noticed is that if I don't specify the area in my ActionLink, e.g.

<%: Html.ActionLink("Test", "Index", "Home")%>

如果我导航到管理"区域,这将停止工作.即我的网址现在是http://localhost/myproj/Admin/Home/Index代替http://localhost/myproj/Home/Index

This will stop working if I have navigated to the "Admin" area. i.e. my url is now http://localhost/myproj/Admin/Home/Index instead of http://localhost/myproj/Home/Index

对这里发生的事情有什么想法吗?

我的路由是创建 MVC 应用程序/区域时的所有默认值.即

My routes are all the defaults when creating an MVC app / Areas. i.e.

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }, 
            new[] { "MyProj.Controllers" } 
        );
    }

和我的区域注册

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Admin_default",
            "Admin/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }

这是故意的吗?这篇文章建议使用 RouteLink 而不是 ActionLink:说使用RouteLink是否需要有区域"如果应用程序按区域分组,则 actionlink 上的路由值?

Is this by design? This posting suggests using RouteLink instead of ActionLink: say to use RouteLink Is it required to have "area" routevalue on actionlink if the application was grouped into areas?

推荐答案

此 StackOverflow 答案 正确地指出,如果您使用区域,则需要提供 Area 名称.

This StackOverflow answer correctly states that you need to provide the Area name if you're using areas.

例如

Html.ActionLink("Home", "Index", "Home", new { Area = "" }, new { })

这篇关于带有区域的 MVC -- Html.ActionLink 返回错误的 URL/路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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