I think it is a safe assumption that every web developer has had to display tabular data at one point or another. Tabular data is easy with ASP.NET: bind a GridView to a data source, and you’re all set. But with ASP.NET MVC, things are a little trickier. We don’t have access to all the nice WebForms controls. Still, it’s fairly easy to do: just write a for-loop, or better yet, use the grid helper from MvcContrib.
We can now combine this with the grid from MvcContrib to produce a collapsable Grid Tree View. This example is encapsulated inside a view user control so that it can be used on any page. It displays imaginary "widgets" in a tree. The widgets aren’t really hierarchical, so I’ve fudged it by making it appear that each widget is a child of its predecessor in the table.
First, let’s create the grid:
That probably looks horrendous, so let’s walk through it. GetWidgets() is a method on the view user control that grabs widgets from wherever (in practice, probably the model or view data). Next, the Hash just contains key/value pairs that are embedded in the opening table tag; here, we’ve specified the table’s ID (by using ClientID, it will have the name that ASP.NET gives to the user control), and we’ve specified that it should be 100% wide. Next, we define the columns using lambda expressions. The first two columns simply display the widget’s name and description. The last column is a little more complicated. It creates a text box using the TextBox helper method. Since the column contains HTML that shouldn’t be encoded, we call DoNotEncode on it. Finally, we use a lambda expression to override how rows are created. The code here populates the row with the ‘child-of-node-#’ class and the id attribute, both of which are needed by ActsAsTreeTable. It may look intimidating, but it’s actually nice once get comfortable with the syntax.
If you set everything up correctly, you should now have a working "grid tree view". In a future article, I’ll introduce a new Html helper that does all the heavy lifting for you.