Tuesday, January 1, 2019

ASP.NET Core 2.2 active navbar menu item


Let's start easy new year and this new blog with a very simple solution to highlight active menu item in an ASP.NET Core 2.2 web application:




In views/Shared/_Layout.cshtml:
<ul class="navbar-nav nav-pills flex-grow-1">
    <li class="nav-item">
        <a id="Home" class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
    </li>
    <li class="nav-item">
        <a id="Privacy" class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
    </li>
</ul>

[...]

@if (ViewData["Active"] != null)
{
    <script type="text/javascript">document.getElementById("@ViewData["Active"]").classList.add("active")</script>
}
Then in Views/Home/Index.cshtml (and similarly for other views):
@{
    ViewData["Title"] = "Home Page";
    ViewData["Active"] = "Home";
}
As you can see, the ViewData["Active"] value matches newly created link id of the active menu item, without any Tag Helper, controller custom attribute or more complicated solutions.

Happy 2019!

No comments:

Post a Comment