ASP.NET Core Active Route Tag Helper

ASP.NET Core Active Route Tag Helper

This C# class will create an anchor tag helper for use in ASP.NET Core. When the current Controller and Action match the specified attributes in an anchor tag, the value “active” will be appended to the class attribute.

To use it, you will need to import a tag helper into your _ViewImports.cshtml file.

@addTagHelper *, CoreWebApplication

Then, wherever you have a navigation anchor html tag, you can add a ASP.NET anchor tag helper. Notice the attribute “asp-nav-item”. Setting this value will active the logic.

<a asp-controller="Home" asp-action="Index" asp-nav-item="true" class="nav-link">Home</a>

Active Route Tag Helper Code

using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace AppName
    [HtmlTargetElement("a", Attributes = "asp-nav-item")]
    public class ActiveRouteTagHelper : TagHelper
        public ViewContext ViewContext { get; set; }

        public string Controller { get; set; }

        public string Action { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
            string currentController = ViewContext.RouteData.Values["Controller"].ToString();
            string currentAction = ViewContext.RouteData.Values["Action"].ToString();

            if (Controller.ToLower() == currentController.ToLower() &amp;&amp; Action.ToLower() == currentAction.ToLower())
                var currentClass = context.AllAttributes["class"];
                string classValue = "active";

                if (currentClass != null)
                    classValue += " " + currentClass.Value;

                TagHelperAttribute classAttribute = new TagHelperAttribute("class", classValue);
Categories: Categories.NET
Tags: Tags
Notify of
Inline Feedbacks
View all comments