views:

267

answers:

1

How do I display hierarical data in ASP.NET? I have a data source that looks like this:

class Tree
{
   IEnumerable<Node> Nodes { get; set; }
}

class Node
{
   string Description { get; set; }
   decimal Amount { get; set; }
   IEnumerable<Node> SubNodes { get; set; }
}

I would like to render is as a list of divs, like the one below. I need the div tags to make the animations smooth when expanding and collapsing the branches.

<ul class="foldable">
   <li>
      <div class="line">
         <div class="description">...</div>
         <div class="amount">...</div>
      </div>
      <div class="line">
         <div class="description">...</div>
         <div class="amount">...</div>
      </div>
      <ul>
         <li>
            <div class="line">
              <div class="description">...</div>
              <div class="amount">...</div>
            </div>
         </li>
      </ul>
   </li>
</ul>
  • I tried building this using ListView elements, but I could not figure out how to call it recursively.
  • I also looked at the TreeView class, but dropped it because it is rendered using tables.
  • I gave up on the CSS Friendly Control Adaptors since this seems to be an either or switch for all the controls on the web site.
  • I tried with a BulledList, but could not figure out how to make it render the divs.

I ended up using four identical nested ListView elements since I know that my lists are never deeper than four levels. But this solution is just so ugly that I'm hoping to find a better one here. =)

+3  A: 

You could use a repeater control and then cycle through your list and for each node that has children nest another repeater. It would take some effort because your would need to use it programmatically, but having a prebuilt Repeater control as a server control would make it quite a bit easier.

I like using repeaters because they're VERY flexible when you take some time and work with them. That, and they don't put in extraneous HTML. :)

Jonathan
Good point! I will move my code to the code-behind file if I don't get a better suggestion, because I actually like the point-and-click programming features that I get when editing markup files in Visual Studio.
Jan Aagaard
If this is the case, then your best bet is nested ListViews, or getting some handy controls developer to develop a custom control for you that can perform your function. Then you're able to use the Design Mode to set attributes.
Jonathan
But I can't have a recursive ListView? :'( That would have been such a beautiful solution.
Jan Aagaard
You can recurse ListViews by nesting them in the front-end, but you must nest the datasources as well, which puts a hefty strain on your database.
Jonathan