2
Answers

MVC Multi Level Menu from database

Mark Tabor

Mark Tabor

8y
1.1k
1
I have a demo project in which i have rendered a menu dynamically from database using Entity Model  I have Add a Model into my Models Folder and in this model i have my menu table (id,parentId,title)
then i have made a menu controller like that
private TestEntities testEntities = new TestEntities();
public ActionResult Index()
{
ViewBag.MenuLevel1 = this.testEntities.Menus.Where(menu=>menu.ParentId==null ).ToList();
return View();
}
 
and in my View--->Menu--->index i have that code
@Model Menu.ModelTest
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<ul>
@foreach (var menuLevel1 in ViewBag.MenuLevel1)
{
<li>@menuLevel1.Name
@if (menuLevel1.Child.Count > 0)
{
<ul>
@foreach (var menuLevel2 in menuLevel1.Child)
{
<li>
@menuLevel2.Name
</li>
}
</ul>
}
</li>
}
</ul>
</div>
</body>
</html>
its working fine and did the good job , Now i want to create a Partial View of that because i want this menu to be called or placed any where any time how to do that .
 
Basically i am newby in MVC i want the layout file just like a master page in asp.net and i want the menu to be dynamic in this layout file. any help please  
Answers (2)