How to create a UrlHelperExtension in ASP.NET Core 3 ? How to Enable automatic setting navbar links to active class in bootstrap when the respective page is accessed or shown

25. April 2020

How to create a UrlHelperExtension in ASP.NET Core 3 ? How to Enable automatic setting navbar links to active class in bootstrap when the respective page is accessed or shown

This following example of creating a HelperExtension method is needed for the problem of making navbar links <li> be active when on the respective page . eg: In the following screenshot you can see the bootstrap navbar with some links .

Now we have to make some functionality so that when we are on the Services page then services Link is highlighted with white font-color. In bootstrap this is done by simply adding active class in <li> like this

 

Now to make it automatically done in asp.net core we will use @Url Helper Extension method .

For that create a Folder Helpers and add one class named as UrlHelperExtensions.cs. Add the code below in this file

using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;

namespace Clanstech.Helpers
{
    
    public static class UrlHelperExtensions
    {
        public static string MakeActive(this IUrlHelper urlHelper,string controller)
        {
            string result = "active";

            string controllerName = urlHelper.ActionContext.RouteData.Values["controller"].ToString();

            if (!controllerName.Equals(controller, StringComparison.OrdinalIgnoreCase))
            {
                result = null;
            }

            return result;
        }
    }
}

Now Add a reference of this class in your _ViewImports.cshtml or You can directly add this in your _Layout.cshtml top of page like this

 

 

Now open the _Layout.cshtml and add the newly created extension helper of Url like this

<li class="nav-item @Url.MakeActive("Home")">
    <a class="nav-link" asp-action="Index" asp-controller="Home" asp-area="Admin">Home <span class='sr-only'>(current)</span></a>
</li>
<li class="nav-item @Url.MakeActive("Services")">
    <a class="nav-link" asp-action="Index" asp-controller="Services" asp-area="Admin">Services </a>
</li>
<li class="nav-item @Url.MakeActive("Pricing")">
     <a class="nav-link" href="#">Pricing </a>
</li>

 

 

 

 

ASP.NET MVC Core , ,