views:

239

answers:

1

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?

+1  A: 

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.

SteadyEddi