【问题标题】:Recursion in Asp.Net Core 2.0Asp.Net Core 2.0 中的递归
【发布时间】: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


【解决方案1】:

我不确定是否有“正确”的做事方式,但我喜欢让我的数据库模型与视图模型不同。我经常使用AutoMapper来获取模型之间的数据。

在你的情况下,我可能有两个视图模型:

public class ProductCategoryItemModel
{
    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 ProductCategoriesModel
{
    public List<ProductCategoryItemModel> Categories { get; set; }
}

我总是转换 ToList() 而不是将 IEnumerable 传递给视图,但我再次不确定这是“正确”的方式。

【讨论】:

    猜你喜欢
    • 2016-12-01
    • 1970-01-01
    • 2018-06-20
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多