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?