I have menu items on the master page
, and if users click on that menu item, I want to show it as active. My goal is to append "Active" to the existing class to indicate that it is active.
_Layout.cshtml:
<div class="menu-items-navigation">
<div class="Classy-item" class="@Html.IsSelected(actions: "Index", controllers: "Classy")">
<a href="@Url.Action("Index", "Classy")" >
<div style="padding-top: 50px;">Classy Items</div>
</a>
</div>
<div class="Regular-stuff">
<a href="@Url.Action("Index", "RegularStuff")">
<div style="padding-top: 50px;">Regular Stuff</div>
</a>
</div>
<div class="Popular-Vessels">
<a href="@Url.Action("Index", "PopularVessels")">
<div style="padding-top: 50px;">Popular Vessels</div>
</a>
</div>
</div>
If I want a menu item to be active
, there is a class called "Active" that I want to give to the corresponding div when a user clicks any of these three menu items.
For example, if I want to make
Regular Stuff as Active when the user clicks
on it, then it will look like this:
<div class="Regular-stuff Active">
If a user clicks on the Classy Item, then:
<div class="Classy-item Active">
This code is referenced from here:
public static string IsSelected(this HtmlHelper html, string controllers = "", string actions = "", string cssClass = "Active")
{
ViewContext viewContext = html.ViewContext;
bool isChildAction = viewContext.Controller.ControllerContext.IsChildAction;
if (isChildAction)
viewContext = html.ViewContext.ParentActionViewContext;
RouteValueDictionary routeValues = viewContext.RouteData.Values;
string currentAction = routeValues["action"].ToString();
string currentController = routeValues["controller"].ToString();
if (String.IsNullOrEmpty(actions))
actions = currentAction;
if (String.IsNullOrEmpty(controllers))
controllers = currentController;
string[] acceptedActions = actions.Trim().Split(',').Distinct().ToArray();
string[] acceptedControllers = controllers.Trim().Split(',').Distinct().ToArray();
return acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController) ?
cssClass : String.Empty;
}
However, I am unsure of how to call this IsSelected method
when a particular menu item is clicked since I cannot use the class attribute twice on the same div.