gpt4 book ai didi

asp.net-mvc - ASP.NET MVC : Generating multi level menu using recursive helpers

转载 作者:行者123 更新时间:2023-12-01 19:33:48 38 4
gpt4 key购买 nike

我正在使用此代码生成菜单,此菜单使用 this technique 从数据库(类别表)填充项目

局部 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>

}
}

我还通过这种方式将模型从 Controller 传递到上面的部分 View :

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; }

}

更新:
使用递归助手是个好主意,但它不会为我生成子菜单。我的问题是什么?
有什么想法吗?

感谢您的建议

最佳答案

最后我通过添加 <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>

}
}

关于asp.net-mvc - ASP.NET MVC : Generating multi level menu using recursive helpers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19213000/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com