3

我想制作嵌套类别..喜欢;

Category 1
   Sub Category 1.1
      Sub Category 1.1.1
         ..
            Sub Category 1.1.1.1.1.1.1.1
Category 2
   Sub Category 2.1
   Sub Category 2.2
      Sub Categry 2.2.1
Category 3

我的数据库shcema;

在此处输入图像描述

我的视图模型;

public class CategoriesViewModel
    {
        public CategoriesViewModel()
        {
            AltGroup = new List<CategoriesViewModel>();
        }

        public int CategoryID { get; set; }
        public string CategoryName { get; set; }    
        public List<CategoriesViewModel> SubCategories{ get; set; }
    }

我的功能;

private List<CategoriesViewModel> GenerateSub(List<Categories> categories)
        {
            List<CategoriesViewModel> categories= new List<CategoriesViewModel>();

            foreach (var child in categories)
            {
                var subCategories = GenerateChildren(child.Categories1.ToList());
                subCategories.Add(new CategoriesViewModel{ CategoryName = child.RoleGroupAdi, SubCategories= subCategories });
            }

            return subCategories;
        }

我的控制器文件;

private DbEntities db = new DbEntities();
public ActionResult KullaniciYetkiGuncelle(int id = 0)
        {
            ViewModel vm = new ViewModdel();
            vm.categories = GenerateSub(db.Categories.ToList());
            return View(vm);
        }

我的观点(我知道我必须改变它);

@foreach (var item in Model.categories)
{
    @item.CategoryName
    <br />
    foreach (var item2 in item.SubCategories)
    {
        @item2.CategoryName
        <br />
        foreach (var item3 in item2.SubCategories)
        {
            @item3.CategoryName
            <br />
        }
    }
}

和结果;虚假上市

Sub Category 1.1
Category 1
   Sub Category 1.1
   Sub Category 1.2
      Sub Category 1.2.1
      Sub Category 1.2.2
      Sub Category 1.2.3
Sub Category 1.2
   Sub Category 1.2.1
   Sub Category 1.2.2
   Sub Category 1.2.3
Sub Category 1.2.1
Sub Category 1.2.2
Sub Category 1.2.3

但它必须是;真实清单

Category 1
   Sub Category 1.1
   Sub Category 1.2
      Sub Category 1.2.1
      Sub Category 1.2.2
      Sub Category 1.2.3

我犯了错误,但我找不到而且我对 View 没有任何想法。

4

2 回答 2

2

您需要将其设为函数,并递归调用它:

@helper PrintCategories(dynamic categories)
{
    foreach (var item in categories)
    {
        @item.CategoryName
        <br />
        var subCategories = item.SubCategories;
        if (subCategories != null && subCategories.Count > 0)
        {
            PrintCategories(subCategories);
        }
    }
}


@PrintCategories(Model.categories)
于 2013-10-03T08:38:08.650 回答
0

我自己找到了解决方案:

当我添加.Where(x => x.ParentCategoryID == null)时,它会返回正确的列表。

据此,控制器变为:

private DbEntities db = new DbEntities();
public ActionResult KullaniciYetkiGuncelle(int id = 0)
{
     var vm = new ViewModdel();
     vm.categories = GenerateSub(db.Categories.Where(x=>x.ParentCategoryID == null).ToList());
     return View(vm);
}

对于视图;检查检查的答案..

于 2013-10-03T18:15:53.117 回答