NavLink Tag Helper


contributed by Alexander Pavlyuk

This tag helper helps creating navbar links that become active when the user sees corresponding page. It works in conjunction with AnchorTagHelper and its asp-controller and asp-action attributes.

Nav links in Bootstrap are li with a inside. When li has class "active", nav link is in active state. ASP.NET 5 AnchorTagHelper provides with a very easy MVC-style way of configuring hrefs of anchor tags - asp-controller and asp-action attributes. NavLinkTagHelper works just like AnchorTagHelper, but creates not just anchor tag, but li tag with anchor tag inside. Moreover, it checks whether specified controller and action are current and sets "active" class for li tag in that case. Works like a magic.

Example

Take a look at nav link at the right side of the navbar for live example.

Code:

<nav-link asp-controller="Samples" asp-action="NavLinkTagHelper">NavLink Tag Helper</nav-link>

Is the same as the following code (when not on that page):

<li>
<a asp-controller="Samples" asp-action="NavLinkTagHelper">NavLink Tag Helper</a>
</li>

Or is the same as the following code (when on that page):

<li class="active">
<a asp-controller="Samples" asp-action="NavLinkTagHelper">NavLink Tag Helper</a>
</li>