clockwiseq
clockwiseq

Reputation: 4229

Attribute Routing With Parameters - Anchor Tag Helper Appending Route-Id Value

I have setup the "basic" routes in Startup.cs with nothing out of the ordinary (one for the standard routing and another for areas). They are below:

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

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

    endpoints.MapRazorPages();
});

Now, with these two, I'm able to navigate (albeit manually) to the routes I want. Below is an attribute route I have on an action:

[Route("Admin/Artists/{artistId:int}/Albums")]
public async Task<IActionResult> Albums(int artistId)
{
    var albums = await Mediatr.Send(new GetAlbumsForArtistRequest { ArtistId = artistId });

    return View(albums);
}

I can successfully browse to that route (albeit manually) and my view appears. I then try using the anchor tag helper:

<a asp-area="Admin" asp-controller="Artists" asp-action="Albums" asp-route-artist-id="@ViewData["ArtistId"]" class="btn btn-info">Albums</a>

The URL that is generated is not correct (and throws an exception as this route is not defined):

/Admin/Artists/Albums

When the correct URL should be:

/Admin/Artists/558/Albums

I have tried finding any help on the Anchor Tag Helper documentation, but it was no help.

Upvotes: 1

Views: 1214

Answers (1)

Fei Han
Fei Han

Reputation: 27825

the correct URL should be: /Admin/Artists/558/Albums

In your code, we can find that you specify asp-route-artist-id="@ViewData["ArtistId"]" for Anchor Tag Helper, which cause the issue.

Please remove - between artist and id, it should be asp-route-artistid.

Test Result

enter image description here

Upvotes: 1

Related Questions