Named Anchor

Named Anchor in ASP.NET Core MVC Tag Helper

Using the asp-fragment for Named Anchor

Recently I’m playing around with the ASP.NET Core MVC tag helpers. I’m very impressed with tag helper to resolve anchor link which are more readable and clean compare to the previous ASP.NET Framework MVC that mixes with C#. However, I got some situation which needs to be resolve using the anchor tag helper, that is using the Named Anchor.

Named anchor has been in HTML for decades. It it one of the most efficient way to jump to certain content on one page flow. Example;

<h2><a id="first" />First Section</h2>
<p>This is the first section – it's just a content</p>

<a href="#first">Go to the first section</a>


<h2><a id="second" />Second Section</h2>
 <p>This is the second section – it's just another content</p>

<a href="#first">Go to the first section</a>
<a href="http://localhost/About/#others">Go to section on other page</a>

This is also very good to be inserted in HTML5 section, especially when you have multiple fragment of contents. By the way, if you look at the HTML code above, you can also use the ‘name‘ attribute instead of ‘id‘. In my case, I prefer to use ‘id‘ attribute so I can refer as selector if needed. Well, that is on HTML document, how about on Razor View document in ASP.NET Core MVC. How do we implement such Named Anchor. At the beginning, I’m confused on how to implement this and so far I cannot find the direct and exact documentation explaining this and I nearly going to create some custom tag helper because of this. I may missed to find the documentation. Fortunately, I first try all of the anchor features to find the solution. Here is what I get from my experience. Suppose you need to have link to other page that has named anchor using tag helper in Razor View document, example;

<a asp-controller="Home" asp-action="About">About</a>

The above code is typical an anchor link in ASP.NET Core MVC and the meaning is straight forward, it will render an anchor link;

<a href="http://localhost/Home/About">About</a>

How do we add the named anchor is actually easy, all you need the the asp-fragment tag helper. For example;

<a asp-controller="Home" asp-action="About" asp-fragment="others">About</a>

With the above code, we finally get the link to point to the named anchor.

<a href="http://localhost/Home/About#others">About</a>

There you go. It is simple, once you know it.

Happy coding! 🙂


Leave a Comment