我的模型如下:
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; }
}
本质上是等级的,&#39; ParentId&#39;提及&#39; Id&#39;作为自我引用。有了这个,我试图按如下方式显示数据:
+--------+-----------------+
| 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 |
+--------+-----------------+
请帮我解决这个问题。
答案 0 :(得分:0)
您可以使用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中有很多例子