从自引用类别表构建并渲染无限层次类别树
我有一个 Categories
表,其中每个类别都有一个 ParentId
,它可以引用我想要显示为多级的任何其他类别的 CategoryId
HTML 列表,如下所示:
<ul class="tree">
<li>Parent Category
<ul>
<li>1st Child Category
<!-- more sub-categories -->
</li>
<li>2nd Child Category
<!-- more sub-categories -->
</li>
</ul>
</li>
</ul>
目前,我正在递归地渲染部分视图并传递下一个类别。它工作得很好,但这是错误的,因为我正在视图中执行查询。
如何将列表呈现为树对象并缓存它以便每次需要所有层次类别的列表时快速显示?
I have a Categories
table in which each category has a ParentId
that can refer to any other category's CategoryId
that I want to display as multi-level HTML list, like so:
<ul class="tree">
<li>Parent Category
<ul>
<li>1st Child Category
<!-- more sub-categories -->
</li>
<li>2nd Child Category
<!-- more sub-categories -->
</li>
</ul>
</li>
</ul>
Presently I am recursively rendering a partial view and passing down the next category. It works great, but it's wrong because I'm executing queries in a view.
How can I render the list into a tree object and cache it for quick display every time I need a list of all hierarchical categories?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建一个自引用的视图模型类。
使用您在视图中执行的查询将其填充到适当的模型类中(或者可能在您的 DataContext 部分类中)。
将执行查询的方法包装在检查结果并将结果存储在
Cache
中的方法中。确保每当对类别树进行更改时都会使缓存失效。
如果查询执行大量查询(每个树级别一个),则考虑将类别表的内容作为平面列表获取,然后使用 linq to object 将其投影到视图模型类中。
Create a view model class that is self referential.
Populate it in the appropriate model class (or perhaps in your
DataContext
partial class) using the query you are executing in the view.Wrap the method that does the query in a method that checks and stores the result in
Cache
.Make sure you invalidate the cache whenever changes are made to the category tree.
If the query executes a lot of queries (one per tree level), then consider getting the contents of the category table as a flat list and then using linq to objects to project it into your view model class.