4

i'm using .net core 3.1.1

in mvc area when i use asp-action like this

<a asp-action="Index2">Index2</a>

it does not properly create the link I want (Does not create area name)

The link it creates:

http://localhost:49770/Home/Index2

But this is the correct link:

http://localhost:49770/admin/Home/Index2

im using endpoint routing as follows:

app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            endpoints.MapAreaControllerRoute(
                "area",
                "Admin",
                "{area:exists}/{controller=Home}/{action=Index}/{id?}"

            );
        });

But when I use the older version of routing (UseMvc)as shown below, it creates the link correctly

 app.UseMvc(routes =>
    {
      routes.MapRoute(
        name : "areas",
        template : "{area:exists}/{controller=Home}/{action=Index}/{id?}"
      );
    });
Mohammad Aghazadeh
  • 2,108
  • 3
  • 9
  • 20
  • Hello, and welcome to Stack Overflow. If I'm understanding you right, I am assuming that these links are from Razor views from within the area, and you're expecting them to implicitly include the area name in the URL since that should be assumed given the context. Is that correct? – Jeremy Caney Mar 01 '20 at 22:12
  • Generally, though, you would usually use the `asp-area` tag helper in conjunction with `asp-action` to specify the target area ([source](https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/areas?view=aspnetcore-3.1#link-generation-with-mvc-areas)). – Jeremy Caney Mar 01 '20 at 22:16

1 Answers1

3

You should modify the order to make the Areas route first :

endpoints.MapAreaControllerRoute(
    "area",
    "Admin",
    "{area:exists}/{controller=Home}/{action=Index}/{id?}"


endpoints.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

So that the <a asp-action="Index2">Index2</a> will create the link to an action method of the same area .

Nan Yu
  • 26,101
  • 9
  • 68
  • 148