Skip to content

Instantly share code, notes, and snippets.

@josephwambura
Last active November 25, 2022 17:46
Show Gist options
  • Save josephwambura/ef97b44c309226301847d3e09e0e2562 to your computer and use it in GitHub Desktop.
Save josephwambura/ef97b44c309226301847d3e09e0e2562 to your computer and use it in GitHub Desktop.
.Net helper to mark Navigation navbar li item as active (MVC and Pages)

How to set navbar item as active when user selects it, in C#

public static class HtmlHelpers
{
    public static string IsSelected(this IHtmlHelper html, string? controller = null, string? action = null, string? page = null, string? pageController = null, string? cssClass = null)
    {
        if (string.IsNullOrWhiteSpace(cssClass))
            cssClass = "active";

        // MVC controllers and actions
        string? currentAction = $"{html.ViewContext.RouteData.Values["action"]}";
        string? currentController = $"{html.ViewContext.RouteData.Values["controller"]}";
        
        // Pages
        string? currentPage = $"{html.ViewContext.RouteData.Values["page"]}";

        // Parent Menus
        if (!string.IsNullOrWhiteSpace(pageController))
        {
            var currentPageList = currentPage.Split('/').ToList();

            currentPageList.RemoveAll(i => string.IsNullOrWhiteSpace(i));

            string? currentPageController = currentPageList.Count == 2 ? currentPageList[0] : string.Empty;

            return pageController == currentPageController ? cssClass : string.Empty;
        }

        if (string.IsNullOrWhiteSpace(controller))
            controller = currentController;

        if (string.IsNullOrWhiteSpace(action))
            action = currentAction;

        if (string.IsNullOrWhiteSpace(page))
            page = currentPage;

        // return for Pages
        if (!string.IsNullOrWhiteSpace(page))
            return page == currentPage ? cssClass : string.Empty;

        // return for MVC
        return controller == currentController && action == currentAction ?
            cssClass : string.Empty;
    }
}
@josephwambura
Copy link
Author

Used as follows:

<a class="dropdown-item @Html.IsSelected(page: "/Demo/Blank")" asp-area="" asp-page="/Demo/Blank"> Blank page </a>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment