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
    {
        [HtmlAttributeNotBound]
        [ViewContext]
        public ViewContext ViewContext { get; set; }

        [HtmlAttributeName("asp-controller")]
        public string Controller { get; set; }

        [HtmlAttributeName("asp-action")]
        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);
                output.Attributes.SetAttribute(classAttribute);
            }
        }
    }
}
Categories: Categories.NET Software Development
Tags: Tags

About Chris

Chris Pounds is a software engineer, entrepreneur, and tech junky. He holds a Bachelor of Science in Information Technology from Western Governors University.

Leave a comment

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