Monday, December 7, 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); %>
<% } %>

No comments:

Post a Comment