Mahyar Esteki
Mahyar Esteki

Reputation: 189

Area is not passed to Url.Action() in ASP.net Core

The following code is working in normal ASP.net MVC.

Url.Action("actionName", "controllerName", new { Area = "areaName" });

But it is not work well in ASP.net Core. Area is recognized as a query string parameter.

How can I solve it? Thanks for any help.

Upvotes: 2

Views: 4229

Answers (1)

itminus
itminus

Reputation: 25360

Make sure you're registering routes as below :

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "areaRoute",
        // if you don't have such an area named as `areaName` already, 
        //    don't make the part of `{area}` optional by `{area:exists}`
        template: "{area}/{controller=Home}/{action=Index}");  

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

I could reproduce the same issue as yours by changing the order of routes, or by changing the {area} to be optional.

  1. The Order matters. The areaRoute should come first. Don't change the order.
  2. When generating url to an area, if you don't have such an area already, don't change the part of {area} to be optional by {area:exists}. For example, let's say you're trying to generate a url to area of MyAreaName:

    Url.Action("actionName", "controllerName", new { Area = "MyAreaName" });
    

    If there's no area named as MyAreaName in your project, and you've made the area optional by:

    routes.MapRoute(
        name: "areaRoute",
        template: "{area:exists}/{controller=Home}/{action=Index}");
    

    the generated url will be controllerName/actionName?Area=MyAreaName.

Upvotes: 5

Related Questions