繁体   English   中英

Asp.Net Core 2.0中的递归

[英]Recursion in Asp.Net Core 2.0

我想制作一个树状结构的产品类别视图。 我发现2011年Ole Michelsen撰写的这篇文章看起来很有希望。 本文介绍了一种与我几乎想到的方法类似的方法,即使用Razor递归渲染树结构。

我的数据库表几乎与文章中描述的表相同:

[ProductCategory]
Id
ParentId
Title

我不确定我的视图模型应该是什么样的。 它应该是ProductCategory的IEnumerable ,还是应该是ProductCategory的实例并在其中包含IEnumerable的ProductCategories?

像这样的东西...

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(当前类别中有多少个产品)?

而我最困惑的是,剃须刀渲染是如何组合在一起的。 如何将viewmodel发送到递归局部视图,以及局部视图如何知道要渲染的项目?

我有一些剃刀代码,但是我可以保证张贴它不会使我想达到的目的变得更清晰。

此伪代码可能更能描述:

_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>

我不确定是否有“正确”的处理方式,但是我希望数据库模型与视图模型保持不同。 我经常使用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传递给视图,但是同样,我不确定这是否是“正确”的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM