Monday, March 2, 2009

Using RenderPartial() to Recursively Display Data

Scenario: You have hierarchical structure with n number of levels. This data must be displayed in nested divs/tables/lists.

Using the ASP.NET MVC framework (currently at RC1), this can easily be achieved using partial views. Here's the jist of it:

In the .aspx view page:

<% foreach(Thing parent in ViewData.Model) { %>

<% Html.RenderPartial("ThingControl", parent); %>
<% } %>

And then in the partial view:

<!-- display single item here -->

<% if (parent.children.Count > 0){ %>
<% Html.RenderPartial("ThingControl", parent); %>
<% } %>

So the exit condition for the recursion is when parent.children.Count is zero. You can include some styling to indent the nested levels if you want, or not. It's very flexible. Once again, ASP.NET MVC proves it is miles above ASP.NET 2.0.