【发布时间】:2017-12-18 20:48:56
【问题描述】:
我想制作一个树状结构的产品类别视图。我从 2011 年开始找到 this article by Ole Michelsen,我认为这看起来很有希望。这篇文章描述了一种类似于我几乎想到的方法,使用 Razor 递归渲染树结构。
我的数据库表和文章中描述的几乎一模一样:
[ProductCategory]
Id
ParentId
Title
我不确定我的视图模型应该是什么样子。它应该是 ProductCategory 的 IEnumerable,还是应该是 ProductCategory 的一个实例并且其中包含 ProductCategories 的 IEnumerable?
类似这样的...
public class ViewModelProductCategory
{
public int Id { get; set; }
public int? ParentId { get; set; }
public string Title { get; set; }
public int SortOrder { get; set; }
public int NumOfProducts { get; set; }
}
...或者更多类似的?
public class ViewModelProductCategory
{
public IEnumerable<ProductCategory> ProductCategory { get; set; }
//public int NumOfProducts { get; set; }//<--Not too sure about this property
public IEnumerable<Product> Products { get; set; }
}
如果第二个更接近“正确”的一个,我怎么会有 SortOrder 和 NumOfProducts(当前类别中有多少产品)?
而我最困惑的是剃刀渲染是如何组合在一起的。如何将视图模型发送到递归分部视图,分部视图如何知道要渲染哪个项目?
我有一些剃须刀代码,但我可以保证发布它不会让我更清楚我想要实现的目标。
这个伪代码也许更能描述:
_recursivePartial.cshtml
@model [my unknown viewmodel goes here, is it IEnumerable or not?]
<ul>
foreach item in model
{
<li>@Html.Partial("_recursivePartial.cshtml", [what goes here?])
// 1: How does _recursivePartial.cshtml know where in the tree it is?
// 2: How does this structure relate to the data structure in the DB?
}
</ul>
【问题讨论】:
标签: c# recursion razor asp.net-core-mvc asp.net-core-2.0