Microsoft .NET MVC Framework: How to Use Named Anchors (URL Hash Links) in Html.ActionLink

In HTML you can specify which part of the page you want to scroll to if a user clicks on a page using the hash symbol (#) like this:

	My Topic

Given how MVC works differently and the URL is translated into controller and action classes, how do you specify if you want your controller/action URL to jump to a specific place on a page when you use Html.ActionLink() method? – as a matter of fact, it is not all that difficult, just look at your IntelliSense signatures of the Html.ActionLink() method. The fragments parameter is what you are looking for.

Let’s say you have a controller called “Home” (very original =)) and an action called “Glossary” which renders a ViewPage with a bunch of term definitions, each at a named link. Now you want to be able to link to each term using the controller and action names but have it jump to the correct term.

If you invoke

Html.ActionLink("My Term", "Glossary", "Home");

you will get to the /home/glossary/ page, no hashes. So, let’s look at the two overrides we can invoke:

Html.ActionLink(string textLink, string actionName, string controllerName, string protocol, string hostName, string fragment, ...)

What we are really interested in is the fragment parameter because that is the one that is going to make the MVC framework add a hash.
So, given your “Home” controller and “Glossary” action, and two named anchors “term1” and “term2” that a view for the “Glossary” actions renders, here’s how we can add such links:

Html.ActionLink("Term 1 Link", "Glossary", "Home", null, null, "term1", null, null);
Html.ActionLink("Term 2 Link", "Glossary", "Home", null, null, "term2", null, null);

Note that null parameters will either use current values (such as protocol) or indicate that there is nothing specified (such as extra HTML attributes for the link). The above two action links would translate into


That is, if you haven’t specified something custom that applies to routing requests.

This entry was posted in MVC and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

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