ASP.NET MVC : Generating multi level menu using re

2019-03-22 17:14发布

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

1条回答
萌系小妹纸
2楼-- · 2019-03-22 17:43

finally I solved my problem by adding <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>

        }
}
查看更多
登录 后发表回答