I need to add an active class with the .nav-link
<ul id="sidebar-nav">
<li >
<a asp-area="DemoArea" asp-controller="Dashboard" asp-action="Index">Dashboard</a>
</li>
</ul>
CodePudding user response:
I have used the static class MenuStateHelper and static method MakeActiveClass along with that I have passed controller name and action method name when both passed values and RouteData value match then it will return active class else it will be null.
public static class MenuStateHelper
{
public static string MakeActiveClass(this IUrlHelper urlHelper, string controller, string action)
{
try
{
string result = "active";
if (!String.IsNullOrEmpty(Convert.ToString(urlHelper.ActionContext.RouteData.DataTokens["area"])))
{
string areaName = urlHelper.ActionContext.RouteData.DataTokens["area"].ToString();
}
if (urlHelper.ActionContext.RouteData.Values != null)
{
string controllerName = urlHelper.ActionContext.RouteData.Values["controller"].ToString();
string methodName = urlHelper.ActionContext.RouteData.Values["action"].ToString();
if (string.IsNullOrEmpty(controllerName)) return null;
if (controllerName.Equals(controller, StringComparison.OrdinalIgnoreCase))
{
if (methodName != null && methodName.Equals(action, StringComparison.OrdinalIgnoreCase))
{
return result;
}
}
}
return null;
}
catch (Exception)
{
return null;
}
}
}
And I have called MakeActiveClass method on Anchor Tag Helper
<a asp-area="@menu.Area" asp-controller="@menu.ControllerName" asp-action="@menu.ActionMethod" >
<i ></i>
<p>
@menu.MenuName
</p>
</a>
CodePudding user response:
Here is a simple demo for dynamic add class by ViewBag value:
<ul id="sidebar-nav">
<li >
<a asp-area="DemoArea" nav-link":"")" asp-controller="Dashboard" asp-action="Index">Dashboard</a>
</li>
</ul>
Backend:
public async Task<IActionResult> Index()
{
ViewBag.Class = true;
return View();
}