I am going to re-order the code a bit so you can see relationship more clearly:
public ActionResult Menus(){
List<Menu> menusource;
ViewBag.Menus = CreateVM(0, menusource);
return View();
}
The block above is creating an empty list and passing to CreateVM, CreateVM returns a populated list which is assigned to the the View using the Viewbag
@{
var menusList = ViewBag.Menus as IEnumerable<MenuViewModel>;
Html.RenderPartial("MenuPartial", menuslist);
}
The menulist is passed as ViewBag.Menus and is passed as a list of menu items into the partial view called "MenuPartial"
The partial view looks like this:
@model IEnumerable<MenuViewModel>
@foreach (var menuitem in model)
{
<ul>
<li>
<h1>@menuitem.Name</h1>
@{
Html.RenderPartial("MenuPartial", menuitem.Children);
}
</li>
</ul>
}
The @model is populated when rendering the view -
Html.RenderPartial("MenuPartial", menuslist);
For each menu item it will display the current list items (menueitem.Name) and then the items children list (going deeper into the hierarchy) and their children and their children etc.
The last part to address is the CreateVM function.
public IEnumerable<MenuViewModel> CreateVM(int parentid, List<Menu> source)
{
return from men in source
where men.ParentId = parentid
select new MenuViewModel(){
MenuId = men.MenuId,
Name = men.Name
Children = CreateVM(men.MenuId, source)
};
}
This routine is also recursively building a list to be displayed. I have underlined where the function calls itself. So in the same way it is building up the list to eventually pass back to the calling routine.
I think what might be missing is how the data is loaded to create the hierarchy. The following is psuedo code but should be illustrative:
List<menuviewmodel> mm = new List<menuviewmodel>();
mm.add(new MenuViewmodel() {id=1, name="one"});
mm.add(new MenuViewmodel() {id=2, name="two"});
</menuviewmodel></menuviewmodel>
Lets add a subitem to the first item
mm[0].Children = new List<menuviewmodel>();
mm[0].Children.add(new MenuViewmodel() {id=10, name="One - One"});
</menuviewmodel>
Now you have a list of MenuViewmodel which also contains another list under the first item of MenuViewmodel.
Hope this helps.