Chronicle
Chronicle

Reputation: 1645

Linking to a specified section of a page using a TagHelper in MVC Core

I have a View called Legal controlled by HomeController

I can link to this page using the anchor tag or with a TagHelper:

<a asp-controller="Home" asp-action="Legal">Cookie policy</a>

In the html in the View Legal there is a section with id="cookies"

With a regular anchor tag, I can have the page automatically scroll there if I do:

<a href="/Legal#cookies">Cookie policy</a>

When I try doing the same in the TagHelper asp-action="Legal#cookies", the anchor is generated with href="/Legal%23cookies", which does not get picked up by my controller.

I've read in this related question how this can be solved using Razor in a regular anchor tag. However, I'd like to do this using a TagHelper. Is there a way to do this?

Upvotes: 5

Views: 2474

Answers (1)

Groxan
Groxan

Reputation: 778

You can use asp-fragment attribute. It defines a URL fragment to append to the URL after #.

<a asp-controller="Home" asp-action="Legal" asp-fragment="cookies">Cookie policy</a>

It will generate HTML:

<a href="/Legal#cookies">Cookie policy</a>

Upvotes: 12

Related Questions