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.

2 comments:

  1. I've used the same technique in Django, using template tags. It works well, but performance can be a drain. Oftentimes you'll have a query for every node in the tree. In Django, I dealt with this by caching a template fragment, because the data changed very rarely. What's the caching support like for MVC?

    ReplyDelete
  2. @Peter: ASP.NET MVC does support caching using the OutputCache action filter

    public class HomeController : Controller
    {
    [OutputCache(Duration = 15)]
    public ActionResult Index()
    {
    ViewData["Message"] = DateTime.Now;
    return View();
    }

    But this caches the whole page, not the action result. There's a cool post on CodeProject where only the ActionResult is cached. Here's a link to that article:
    Action Result Caching

    ReplyDelete