Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic sub menu in C# MVC

In my app I am trying to make a dynamic menu. What I am doing is something like this.

1 - I have a model

public class Menu
{
    public String LinkText;
    public String ActionName;
    public String ControllerName;
    public String OrganizationId;
    public String SubMenuLabel;
}

2 - I have a controller which adds menu items to a list which corresponds to the above model.

List<Menu> menu = new List<Menu>();
menu.Add(new Menu { LinkText = org.Name, ActionName = "Index", ControllerName = "Organization", OrganizationId = org.Id, SubMenuLabel = "Go To" });
ViewBag.menu = menu;

On the view side I loop over the menu and display the menu. The issue I am having is with sub menus. I am struggling to put the logic for sub menu together. Right now I have a sub menu label if that exist I display it in a drop down, but if I have multiple entries in a sub menu it doesn't work.

The code for the view is this

@foreach (var item in ViewBag.menu)
       {
          <li class="divider"></li>
            if (!String.IsNullOrEmpty(@item.SubMenuLabel))
                {
                <li class="has-dropdown not-click">
                    <a href="#">@item.SubMenuLabel</a>
                    <ul class="dropdown">
                        <li><a href="/@item.ControllerName/@item.ActionName/@item.OrganizationId" class="">@item.LinkText</a></li>
                    </ul>
                </li>
                }
                else
                {
                <li>
                    <a href="/@item.ControllerName/@item.ActionName/@item.OrganizationId" class="">@item.LinkText</a>
            </li>
        }
      }

Any ideas??

like image 312
mohsinali1317 Avatar asked Dec 09 '25 05:12

mohsinali1317


1 Answers

What if you were having a list of Menu object as subMenu?

public class Menu
{
    public String LinkText;
    public String ActionName;
    public String ControllerName;
    public String OrganizationId;
    public List<Menu> SubMenus;
}

And then having a nested foreach inside your view :

@foreach (var item in ViewBag.menu)
   {
      <li class="divider"></li>
        if (item.SubMenu != null){
             @foreach (var subMenu in item)
             {
               ...
             }
        }
        else
        {
            <li>
                <a href="/@item.ControllerName/@item.ActionName/@item.OrganizationId" class="">@item.LinkText</a>
        </li>
        }
  }
like image 150
Deblaton Jean-Philippe Avatar answered Dec 11 '25 20:12

Deblaton Jean-Philippe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!