ASP.NET MVC:使用递归帮助器生成多级菜单 [英] ASP.NET MVC : Generating multi level menu using recursive helpers

查看:330
本文介绍了ASP.NET MVC:使用递归帮助器生成多级菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using this code for generating menu, this menu populates items from database (Category Table) using 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>

        }
}

我也以这种方式将模型从控制器传递到上面的局部视图:

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

我的类别模型:

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?

感谢您的建议

推荐答案

最后,我通过添加<ul class="dropdown-menu">解决了我的问题:

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>

        }
}

这篇关于ASP.NET MVC:使用递归帮助器生成多级菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆