Menu Dynamic ASP.NET MVC5 Razor
Model Menu:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Models
{
public class Menu
{
public int ID { get; set; }
public string Nom { get; set; }
public string Description { get; set; }
public string Lien { get; set; }
public int Ordre { get; set; }
public int OidMenuParent { get; set; }
}
}
Controller
public class HomeController : Controller
{
public MenuRepository menurepository = new MenuRepository();
public ActionResult Index()
{
var viewmodel=new HomeViewModel
{
Menus=this.menurepository.All,
};
return View(viewmodel);
}
}
View Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Models;
namespace ViewModels
{
public class HomeViewModel
{
public IEnumerable<Menu> Menus { get; set; }
}
}
View
<ul class="nav navbar-nav navbar-left">
@{var menus=Model.Menus;}
@{var menusparent = (from mp in menus where mp.OidMenuPatent==0 select mp).ToList();}
@foreach (var item in menusparent)
{
var query = (from mc in menus where mc.OidMenuPatent == item.ID select mc).ToList();
if (query.Count() > 0) {
<li class="dropdown active">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">@item.Description <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
@foreach (var childmenu in query)
{
<li>@Html.ActionLink(@childmenu.Description, @childmenu.Lien, "Home")</li>
}
</ul>
</li>
}
else {
<li>@Html.ActionLink(@item.Description, @item.Lien, "Home")</li>
}
}
</ul>