I have a side menu in my site, which is currently a load of list items:
<ul>
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
Now I need to change this to have sub items, so that it renders…
<ul>
<li>
<ul>
<li>...</li>
<li>...</li>
</ul>
</li>
<li>...</li>
<li>...</li>
</ul>
I have a list of items like so:
/// <summary>
/// Gets the admin menu items.
/// </summary>
/// <returns></returns>
public IQueryable<IAdminMenuItem> GetAdminMenuItems()
{
return new List<IAdminMenuItem> {
new AdminMenuItem {MenuItemId = "100", DisplayText = "xxx", ParentId = "" ControllerName = "xxx", ActionName = "xxx"},
new AdminMenuItem {MenuItemId = "101", DisplayText = "xxx", ParentId = "100" ControllerName = "xxx", ActionName = "xxx"},
new AdminMenuItem {MenuItemId = "102", DisplayText = "xxx", ParentId = "100" ControllerName = "xxx", ActionName = "xxx"},
new AdminMenuItem {MenuItemId = "200", DisplayText = "xxx", ParentId = "" ControllerName = "xxx", ActionName = "xxx"},
new AdminMenuItem {MenuItemId = "201", DisplayText = "xxx", ParentId = "200" ControllerName = "xxx", ActionName = "xxx"},
new AdminMenuItem {MenuItemId = "202", DisplayText = "xxx", ParentId = "200" ControllerName = "xxx", ActionName = "xxx"},
}.AsQueryable();
If a list item doesn’t have a ParentID then it is a top level element. If it does, it is a sub item element.
I’ve got this code in at present to cope with the flat menu structure:
<ul>
@foreach (Avelo.Exchange.WebUI.Domain.Interfaces.IAdminMenuItem item in Model){
<li><a href="@Url.Action(item.ActionName, item.ControllerName)"><span>@item.DisplayText</span></a></li>
}
</ul>
I suppose my first question is how would I handle the sub menu items in the view, but I would also like to future proof the solution by it being able to handle further sub levels (i.e. three steps down rather than just two). I’ve heard of recursive looping, but have no idea how to implement it. Is this a good way to go?
Thanks in advance
S
I have had a similar problem some time ago. I’ll try to adapt my solution to your model.
I guess you have something like this:
As you can see I’ve changed your property ParentId with a collection of Children cause it’s easier to manage.
In your view you would populate your menu (and all the submenus) and pass it to the view:
This is my view.
There is not much in here.
I’ve created an helper which will be in charge of creating your menu and all the submenus (with recursion):
This helper can be improved and surely someone might object that it can be done in a better way but I didn’t have much time to perfect it. Sorry for that.
You can find some code here. The project is called Mvc3SubMenus.