MVC with Areas — Html.ActionLink returning wrong URL/Route?

有些话、适合烂在心里 提交于 2019-12-07 01:52:29

问题


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 )%>

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

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

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

Any ideas on what is going on here?

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

And my area registration

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

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?


回答1:


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

eg.

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


来源:https://stackoverflow.com/questions/6132248/mvc-with-areas-html-actionlink-returning-wrong-url-route

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