我使用此代码生成菜单,此菜单使用this technique
填充数据库(类别表)中的项目部分视图
@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>
}
}
我也是这样将模型从控制器传递到局部视图以上:
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);
}
我的分类模型:
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; }
}
更新:
使用递归助手是个好主意,但它不会为我生成子菜单。我的问题是什么?
任何想法?
感谢您的建议
答案 0 :(得分:5)
最后我通过添加<ul class="dropdown-menu">
来解决了我的问题:
@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.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())
{
<ul class="dropdown-menu">
@ShowTree(item.Children)
</ul>
}
</li>
}
}