Learning Learning - 4 months ago 13
ASP.NET (C#) Question

How to append active class to existing class on clicked menu items?

I have

menu items on master page
and if users click on that menu item I want show it active. I want to append Active to existing class to make it 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>


Now if I want this menu item to be
Active
I have 1 class called as Active in which I want to give to this div if user click any of this 3 menu items.

For eg:If I want to make
Regular Stuff as Active when user clicks
on it then it will be like this:

<div class="Regular-stuff Active">


If user click on Classy Item then :

<div class="Classy-item Active">


Code taken from here Reference:

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;
}


But I am confused here that how to class this Isselected method when particular menu items will be clicked as i cant use class attributes 2 times on div.

Can anybody please help me with this??

Answer

You are right, you can't declare the class attribute twice, but you can combine them like this:

<div class="Classy-item @Html.IsSelected(actions: "Index", controllers: "Classy")">

Which will render if not selected:

<div class="Classy-item "> 

Or render this if selected:

<div class="Classy-item Active">
Comments