What is the best way to add an active class to a clicked menu item that already has a class

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.

Answer №1

It is correct that you cannot declare the class attribute twice, but you have the option to combine them as shown below:

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

This will be rendered if not selected:

<div class="Classy-item "> 

Alternatively, it will be rendered like this if selected:

<div class="Classy-item Active">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I extract data from Google Calculator using Json in a Windows Phone 7 app written in C#

Currently in the process of developing a WP7 application that involves implementing a currency exchange functionality. Although I could use CSV for this purpose, I've encountered limitations in the C# Silverlight libraries whenever I attempt to work w ...

Which Javascript/Css/HTML frameworks and libraries would you suggest using together for optimal development?

Interested in revamping my web development process with cutting-edge libraries, but struggling to navigate the vast array of tools available. The challenge lies in finding a harmonious blend of various technologies that complement each other seamlessly. I& ...

Adjusting the width of the rail in Material UI's vertical Slider component in React

After attempting to adjust the width and height of the rail property on the material ui slider I obtained from their website demo, I have encountered an issue with changing the thickness. import React from "react"; import { withStyles, makeStyles } from " ...

Set a CSS rule to style every other row in a table, starting from the second row and resetting after

Is there a way to refresh the even and odd count in CSS whenever a specific row is shown? Here's an example setup: header header header even even even odd odd odd Subhead Subhead Subhead even even even How can I ensu ...

"Comparison: Utilizing HTML5 Video Player with IE8 Embed Fallback versus Implementing Fixed

This dilemma has me at my wit's end. In an HTML5 Video element, I've included an mp4, ogg, and an embedded mp4 fallback. However, on the embed fallback in IE8, all my attempts to position the fixed element (#fixed) above it with z-indexing have f ...

What is the process for incorporating themes into CSS?

At the moment, I have set up variables to manage colors for both light and dark themes (such as --light-background-color, --dark-background-color). Handling two themes is manageable with this approach, but it feels a bit labor-intensive. If more themes wer ...

Unable to show the name of the chosen file

After customizing the input [type = file], I successfully transformed it into a button with a vibrant green background. Here is the code snippet that enabled this transformation: <style> #file { height:0px; opacity:0; } ...

Obtaining the value of an item in an unordered list

Hi everyone, I have been trying to extract the value of <li> elements that display images horizontally. Below is the HTML code I am working with: <div id="layoutInnerOptions"> <ul id="navigationItemsContainer" class="layouts_list"> <l ...

Struggling with the conversion of JSON data into a FHIR Appointment object

After fetching the following json data: { "fullUrl": "https://my.fhir-server.com:8181/multi-m2integrationtest/firm/xyz123/ema/fhir/v2/Appointment/7240", "resource": { "resourceType": "Appointment", ...

jquery hover effect not functioning properly

I have a question regarding my jquery mobile application. I am trying to implement a hover effect on items with the class grid-item, where the width and height change simultaneously in an animation. Here is the code snippet I am using: $('.grid-i ...

Tips for displaying content in a stacked format when hovering, similar to a list item (<li>), using jquery/javascript

I am attempting to display different content on hover over text, specifically listing various HTTP error codes. My setup includes 3 icons and text that will reveal specific content based on the text hovered over: success error blocked Below is the JS cod ...

What are the steps to resolving the problem of enabling a feature in OrchardCore CMS?

As I work on creating a new feature for OrchardCore CMS by following the official tutorial, I encountered an issue. When attempting to enable the feature in the CMS admin panel, the server returned a 405 HTTP status code and displayed a blank page. Despite ...

What is the best way to combine a string with a variable in sass?

Is there a way to merge a string and a variable in Sass to form a variable name that is already present? $size: "sm"; $button-sm: 1rem; $buttom-md: 1.5rem; body { font-size: $button-#{$size}; } The desired output is: body { font-size: 1r ...

Using IsTabStop attribute with an Image control: All you need to know

In my form, I have multiple textboxes and an Image control. The textboxes are designed to gain focus when the "tab" key is pressed due to their 'IsTabStop' property being set to true. Unfortunately, the Image control does not have this property, ...

Encountering a C# ASP.NET error while attempting to parse JSON data from a file using JObject

I'm attempting to run the following code: JObject settingsInfo = JObject.Parse(File.ReadAllText("settings.json")); const string ServerName = (string)settingsInfo["servername"]; Despite its apparent simplicity, I am consistently encountering the fol ...

Navigating with Angular Material and md-nav-bar for efficient routing

Currently, I am delving into Angular and have opted to utilize the Angular Material library for my initial application. After tweaking some basic code borrowed from this source, which I adjusted to suit my requirements, I encountered difficulties with rout ...

Installing an Asp.net Application on IIS 7

When deploying my Asp.net application on the IIS server, I encountered an error. However, when running the application on my server, everything works fine with no issues. I have a static HTML website with a tool folder within the site's folder, where ...

Is it possible to recognize when the mouse button is held down and the cursor is outside the viewport by using mouseleave detection?

Is there a way to detect when a user moves the mouse outside of the view-port, even if they are holding down the mouse button (for example, if the mouse is on the browser address bar)? In the code below, I am currently using mouseout and mouseleave to det ...

Save Datagrid to excel in an application built with asp

Looking for advice on the most efficient method to export a Datagrid to excel. I have very little experience with this task and would appreciate any insights or tips on how you guys usually approach it. I've heard there are multiple ways to do it, but ...

Specialized hover mission

Do you have a question? Imagine you have 3 spans where the default color is black. When you hover over a span, its color changes to red. But what if I told you that at the start, the first span has an orange color. Now, I want to hover over the orange on ...