Get ASPNET Core Razor Page name in _Layout file to update navigation items

Viewed 2792

Using Bootstrap 4 and need to add the active class to navigation items to reflect current Razor page (new razor pages in Core 2.0). How can I find out which page/controller I am on so I can add the active class name to the proper:

<li><a class="active">...

Thanks.

Update: I was able to solve this with the following code in my page initializer:

@{
    var _action = this.Url.ActionContext.ActionDescriptor.DisplayName;
    var NavDashboard = "/abc";
    ...
}

Then I can add the "active" class in each nav items like:

<a asp-page="@NavDashboard" class="nav-link@(_action=="@NavDashboard" ? " active" : string.Empty)">Dashboard</a>

Rinse and repeat for each nav item.

1 Answers

I'd go with a custom tag helper to add the active class to an element.

I forked Ben Cull's ActiveRouteTagHelper for MVC and modified it for Razor Pages and called it ActivePageTagHelper. It's used similarly to his, like this:

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li is-active-page asp-page="/Index"><a asp-page="/Index">Home</a></li>
        <li is-active-page asp-page="/About"><a asp-page="/About">About</a></li>
        <li is-active-page asp-page="/Contact"><a asp-page="/Contact">Contact</a></li>
    </ul>
</div>
Related