Build and render infinite hierarchical category tree from self-referential category table
- by FreshCode
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?