I\'m setting a Menu with Sub-menu
display Sub-categories
, in database I created a column isSelected
with Boolean data type. If only
Check if this helps.
public abstract class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
IEnumerable<MVC3Stack.Models.MenuItem> menus = BuildMenu();
ViewBag.Menus = menus;
//base.OnActionExecuting(filterContext);
}
private IEnumerable<MVC3Stack.Models.MenuItem> BuildMenu()
{
IEnumerable<MVC3Stack.Models.MenuItem> menus = new List<MVC3Stack.Models.MenuItem>
{
new MVC3Stack.Models.MenuItem{Id = 1, Level = 0, ParentId = 0, Text = "Main", Url = Url.Action("Index", "Home"), IsSelected=true, HasChildren=true },
new MVC3Stack.Models.MenuItem { Id = 2, Level = 1, ParentId = 1, Text = "Main-SubMenu1", Url = Url.Action("Index", "Home"), IsSelected=false, HasChildren=false },
new MVC3Stack.Models.MenuItem { Id = 3, Level = 1, ParentId = 1, Text = "Main-SubMenu2", Url = Url.Action("Index", "Home"), IsSelected=true , HasChildren=false},
new MVC3Stack.Models.MenuItem { Id = 4, Level = 0, ParentId = 0, Text = "Second Menu", Url = Url.Action("Index", "Home") ,IsSelected=true, HasChildren=true},
new MVC3Stack.Models.MenuItem { Id = 5, Level = 1, ParentId = 4, Text = "Second Menu-SubMenu1", Url = Url.Action("Index", "Home"),IsSelected=true, HasChildren=false }
};
return menus;
}
}
Here is the _layout.cshtml
@{
var topLevel = ((IEnumerable<MVC3Stack.Models.MenuItem>)ViewBag.Menus).Where(x => x.Level == 0);
}
<ul id="menu">
@foreach (var item in topLevel)
{
if (item.IsSelected)
{
<li>
<a href="@Url.Action("Index", "Home")">@item.Text</a>
@if (item.HasChildren)
{
var level1 = ((IEnumerable<MVC3Stack.Models.MenuItem>)ViewBag.Menus).Where(x => x.Level == 1 && x.ParentId == item.Id);
<ul>
@foreach (var item1 in level1)
{
if (item1.IsSelected)
{
<li>
<a href="@Url.Action("Home", "Index")">@item1.Text</a>
</li>
}
}
</ul>
}
</li>
}
}
</ul>
This can give you some pointers on how to implemente this. Note: Number of levels will be fixed with this solution.