简体   繁体   中英

MVC5 Url.Action returns null inside area

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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