I am using this code for generating menu, this menu populates items from database (Category Table) using this technique
Partial View :
@using SarbarzDarb.Helper
@model IEnumerable<SarbarzDarb.Models.Entities.Category>
@ShowTree(Model)
@helper ShowTree(IEnumerable<SarbarzDarb.Models.Entities.Category> categories)
{
foreach (var item in categories)
{
<li class="@(item.ParentId == null && item.Children.Any() ? "dropdown-submenu" : "")">
@Html.ActionLink(item.Name, actionName: "Category", controllerName: "Product", routeValues: new { Id = item.Id, productName = item.Name.ToSeoUrl() }, htmlAttributes: null)
@if (item.Children.Any())
{
ShowTree(item.Children);
}
</li>
}
}
also I'm passing model from controller to above partial view this way :
public IList<Category> GetAll()
{
return _category.Where(category => category.ParentId == null)
.Include(category => category.Children).ToList();
}
public ActionResult Categories()
{
var query = GetAll();
return PartialView("_Categories",query);
}
my Category Model:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public virtual Category Parent { get; set; }
public virtual ICollection<Category> Children { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
Updated :
using recursive helpers are good idea but it doesn't generate sub-menu for me. what's my problem?
Any Idea?
Thanks in your advise