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;

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;

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;

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

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

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

Happy coding! 🙂

 

Leave a Reply

Your email address will not be published. Required fields are marked *