How to Dynamically Change CSS of Menu Item Using jQuery on Click Event

Currently, I am in the process of creating an ASP.NET-MVC 4 application. One interesting aspect of this project involves dynamically loading the menu within the layout page. To accomplish this task, I have devised a method that utilizes a partial view specifically designed for loading menus dynamically.

Within MenuModel.cs:

public class MenuModel
{
    public List<MainMenu> MainMenuModel { get; set; }        
}

public class MainMenu
{
    public int MainMenuID;
    public string MainMenuName;
    public string MainMenuController;
    public string MainMenuAction;
}

Then, PartialController.cs contains the following logic:

using Insights.Models;

[ChildActionOnly]
public ActionResult LoadMenu()
{
    MenuModel ObjMenuModel = new MenuModel();
    ObjMenuModel.MainMenuModel = new List<MainMenu>();
    ObjMenuModel.MainMenuModel = GetMainMenu();
    return PartialView(ObjMenuModel);
}

public List<MainMenu> GetMainMenu()
{
    List<MainMenu> ObjMainMenu = new List<MainMenu>();
    var context = new InsightsEntities();
    ObjMainMenu = context.Insights_mMenu.Where(m => m.parentMenuUID == 0).Select(x => new MainMenu()
        {
            MainMenuID = x.menuUID,
            MainMenuName = x.menuName,
            MainMenuController = x.menuURLController,
            MainMenuAction = x.menuURLAction
        }).ToList();

        return ObjMainMenu;
}

The corresponding Partial View, LoadMenu.cshtml, is defined as follows:

@model Insights.Models.MenuModel

<link rel="stylesheet" href="~/MADMIN_files/style(2).css" />
<ul class="sidebar-menu on-click" id="main-menu">
<li class="active">
    <div class="sidebar-menu-item-wrapper">
        <a href="#">
            <i class="icon-home"></i>
            <span>Home</span>
        </a>
    </div>
</li>
@{
    foreach (var MenuItem in Model.MainMenuModel)
    {

    <li class="active">
        <div class="sidebar-menu-item-wrapper">
            <a href='@Url.Action(@MenuItem.MainMenuAction, @MenuItem.MainMenuController)'><span>@MenuItem.MainMenuName</span></a>
        </div>
    </li>

     }
  }
</ul>

Lastly, in _Layout.cshtml, we include the menu by calling the LoadMenu action from the Partial Controller:

<div id="sidebar">
     @{ Html.RenderAction("LoadMenu", "Partial"); }
</div>

To illustrate these elements in action, refer to my screen capture: https://i.sstatic.net/Eykpv.jpg

In the displayed interface, you will notice the page associated with the "Reports" menu. My goal is to differentiate the clicked menu by visually highlighting it using specific CSS classes such as "active" and "inactive". Do you have any suggestions on how best to implement this functionality considering the dynamic loading nature of the menus?

Answer №1

To identify the 'Parent' action and controller name from within the Child action, you can utilize the following code snippet. By comparing these values to each menu item, you can determine the active menu item and set an IsActive property accordingly. Then, use the IsActive property to control the addition of a css class during menu rendering.

string parentAction = this.ControllerContext.ParentActionViewContext.RouteData.Values["action"].ToString();
 string parentController = this.ControllerContext.ParentActionViewContext.RouteData.Values["controller"].ToString();

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

Ajax waits for the animation to finish before proceeding

This topic has been previously discussed on stackoverflow, but none of the solutions have helped me solve my issue. I am utilizing the "form" jQuery plugin in the following manner: $(document).ready(function() { $('#myForm').ajaxForm({ ...

Tips for incorporating Action Links into your CSS workflow

<li class="rtsLI" id="Summary"><a href="javascript:void(0);" onclick="javascript:rtsXXX.OnClientTabSelected(this‌​, 0);" class="rtsLink"><span class="rtsTxt">Test</span></a></li> I have made a change by replacing th ...

Using jQuery Datatable on dropdown selection change

For my projects, I rely on Jquery Datatable and it functions perfectly on page load. However, I am facing a challenge where I need to trigger the datatable on dropdown change. I have searched through various resources but have not found a satisfactory sol ...

Having trouble customizing the appearance of wtform attributes

Hello Everyone, Here is the content of the .py file: from flask import Flask, render_template, flash, session, redirect, url_for from flask_wtf import FlaskForm from wtforms import StringField,SubmitField from wtforms.validators import Da ...

Is it possible for a div to contain more than one class in Twitter Bootstrap?

Is it possible for a div element to have multiple classes assigned to it? I am currently working with Twitter Bootstrap and I would like to utilize two predefined classes. Specifically, I want to apply the active class to a dropdown-toggle within a navig ...

How can a logo be adjusted in a bootstrap navbar when the browser is resized or when the user zooms in or out?

I have been struggling for the past 4 hours to find a solution to scale an image when the browser is resized. The website I am working on uses bootstrap and the image is located in the navbar-brand section. Typically, navbar-brand is used for a logo, but i ...

Ensure that the dropdown menu remains at the forefront of all other elements

I am facing an issue with a dropdown menu that changes the language. The problem occurs when the list of languages gets longer and the menu ends up behind other elements on the page. I'm not sure what needs to be changed or which CSS properties I nee ...

all-encompassing ajax call method with jquery

Is there a universal function for calling ajax requests globally? For example, instead of writing the same code multiple times: $.ajax({ url: some_url_address, type: 'post', data: $('#form').serialize(), dataType: &apos ...

Reveal a segment of a picture

Is there a way to display only a section of an image using either jQuery or another JavaScript method? For example: image: [ ] [ -------- ] [ - - ] [ - part - ] [ - - ] [ -------- ] [ ...

What is the best way to incorporate a YouTube channel into a webpage once the document is fully loaded?

I have a YouTube embedded channel from a particular company, and below I have links to other related companies. However, this is just a widget on my page. When I click a link in the list, I want to load the new embedded YouTube channel from the other compa ...

Attempting to compare the HTML datetime with the current time in order to implement conditional formatting

I am working with a SharePoint discussion list that includes a field named "Last Updated." My goal is to identify and highlight rows where the last update was more than 1 hour ago. Here is my current approach: <html> <head> <sc ...

Dropdown menu remains unable to open

One of the dropdown menus on my website is not retracting back properly, but only on the contact page where a Google map is displayed. The issue looks like this: I've tried tweaking the CSS code without success. What could I be missing? Should I prov ...

I am looking to postpone the execution of the jQuery ajax success callback function

I'm looking for a way to introduce a delay of 2 seconds before the content inside this block changes. Could you assist me in setting a timer so that the ajax request doesn't happen too quickly, allowing time for some animation to be displayed? I ...

How can you toggle the visibility of a div based on detecting a specific class while scrolling?

My webpage features a sticky header that gains an extra .header-scrolled class when users scroll down. I am looking to switch the logo displayed in the header once it has been scrolled. Below is a simplified version of my HTML code: <header class=".he ...

The jQuery UI datepicker struggles to show the entire year in its year selection menu

Recently, I developed a function within an MVC Struts application's JSPs that sets up a generic jQuery-UI datepicker. Here is the code: function setUpGenericDate(id) { var d=new Date(); $("#" + id).datepicker({ duration: 'fa ...

Steps for invoking a method from a controller

I am currently in the process of developing a website similar to Planning Poker. One issue I am facing is figuring out how to delete games once they have been created. Specifically, I am struggling with calling gamesremoveALL from my controller. Below is ...

Having trouble getting Jqwidgets to function properly in MVC4

I am currently integrating jqwidgets into my asp.net mvc4 project, but I keep encountering an error "Uncaught TypeError: Cannot read property ‘dataAdapter’ of undefined" in the code below. Please note that this code snippet is just a demonstration of t ...

Revamp Your Navbar Links with Bootstrap Color Customization

Even though this topic has been discussed extensively, I still haven't found a solution that works for me. My goal is simple - to change the color of the links in my bootstrap navbar to white. I know that the CSS is correctly applied because I can adj ...

Utilizing the power of Scoped CSS with Bootstrap/Bootstrap-Vue Integration

I'm currently working on a chrome extension and utilizing Bootstrap-Vue in my Vue files. I have imported bootstrap/bootstrap-vue into my js file, but the styling is being applied globally. Is there a way to scope the Bootstrap only onto specific inser ...

Tips for aligning 2 divs in the same position?

I am working on a slider feature that includes both videos and pictures. I need to ensure that the videos are hidden when the device width exceeds 600px. Here is the HTML code snippet: <video class="player__video" width="506" height="506" muted preloa ...