代码之家  ›  专栏  ›  技术社区  ›  Mr. Lumos

显示嵌套数据(层次结构),MVC3

  •  0
  • Mr. Lumos  · 技术社区  · 11 年前

    我的模型如下:

    public class Category
    {
        [Key]
        public int Id { get; set; }
    
        [StringLength(200), Required, DataType(DataType.Text)]
        public string Title { get; set; }
    
        [Display(Name = "Parent Category")]
        public int? ParentId { get; set; }
    
        [DisplayFormat(NullDisplayText = "Root")]
        public virtual Category ParentCategory { get; set; }
    
        public virtual ICollection<Category> ChildCategories { get; set; }
    }
    

    本质上是分层的,“ParentId”引用“Id”作为自引用。使用此选项,我尝试按如下方式显示数据:

    +--------+-----------------+
    | S. No  |        Name     |
    +--------+-----------------+
    |   1    |  Parent One     |
    +--------+-----------------+
    |   1.1  |  Child-1 of One |
    +--------+-----------------+
    |   1.2  |  Child-2 of One |
    +--------+-----------------+
    |   2    |  Parent Two     |
    +--------+-----------------+
    |   2.1  |  Child-1 of Two |
    +--------+-----------------+
    |   3    |  Parent Three   |
    +--------+-----------------+
    

    请帮助我。

    1 回复  |  直到 11 年前
        1
  •  0
  •   Community CDub    8 年前

    您可以按parentId使用组计算总子数,然后计数

    这是我的解决方案

    定义ViewModel

    public class CategoryViewMoel
    {
        public IEnumerable<ParentCategoryInfo> parentCategoryInfo { get; set; }
        public int SN { get; set; }
        public int ChildSN { get; set; }
    }
    
    public class ParentCategoryInfo
    {
        public int? ParentId { get; set; }
        public int TotalChild { get; set; }
    }
    

    在控制器中

    var model = new CategoryViewMoel();
    
    var parentCategory =  from r in db.Categories
                          where r.ParentCategory != null
                          group r by r.ParentId into newGroup
                          select new ParentCategoryInfo 
                          {
                              TotalChild = newGroup.Count(),
                              ParentId = newGroup.Key,
                          };
    model.SN = 1;
    model.ChildSN = 1;
    model.parentCategoryInfo = parentCategory;
    

    最后在您的视图中

    <table>
    <thead>
        <tr>
            <th>S. No</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
            @foreach (var parent in Model.parentCategoryInfo)
            {
                <tr>
                    <td>@Model.SN </td>
                    <td>Parent @Model.SN</td>
                </tr>
    
                for (var i = Model.ChildSN;  i <= parent.TotalChild; i++)
                {
                    <tr>
                        <td>@Model.SN.@i</td>
                        <td>Child - @i of @Model.SN</td>
                    </tr>
    
                Model.ChildSN = 1;
                Model.SN++;
            }
    </tbody>
    

    数字到单词的映射可以通过构建一个定制的助手函数来实现,SO中有很多示例

    converting numbers in to words C#