Build and render infinite hierarchical category tree from self-referential category table

Posted by FreshCode on Stack Overflow See other posts from Stack Overflow or by FreshCode
Published on 2010-04-13T11:06:32Z Indexed on 2010/04/13 11:13 UTC
Read the original article Hit count: 548

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?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about hierarchical-trees