Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 788
Chronicle Avatar asked Jan 27 '23 18:01

Chronicle


1 Answers

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>
like image 98
Groxan Avatar answered Feb 06 '23 16:02

Groxan