Rewriting the MvcContrib Grid part 2 - New Syntax

This is part two of a series on the new MvcContrib grid component.

Edit: 28 Feb 09 I have removed the use of Partial views in the latest MvcContrib trunk for certain areas where it didn't really make sense. The examples below have been updated to reflect this.

The updated version of the MvcContrib grid has a new syntax that uses method chaining and lambda expressions to build a fluent interface. Here is a grid defined with the new syntax:

<%= Html.Grid(Model.People).Columns(column => {
     		column.For(x => x.Id).Named("Person ID");
     		column.For(x => x.Name);
     		column.For(x => x.DateOfBirth).Format("{0:d}");
     	})
        .Attributes(style => "width:100%")
     	.Empty("There are no people.")
     	.RowStart(row => "<tr foo='bar'>") %>

Compare this to the same grid defined using the old syntax:

<%
  Html.Grid(Model.People,
    new Hash(empty => "There are no people", style => "width:100%"),
    column => {
	column.For(x => x.Id, "Person Id");
     	column.For(x => x.Name);
     	column.For(x => x.DateOfBirth).Format("{0:d}");
    }, sections => {
       sections.RowStart(item => { %>
          <tr> <!-- some custom html for the row start here -->
   <% });
%>

Note how grid options (eg Empty) are now specified as part of the fluent interface rather than part of the HTML Attributes dictionary (which I always felt was messy). The use of method chaining also means that it is no longer possible to embed html blocks inside the grid definition (eg RowStart). However, you can still achieve the same functionality using the RowStart method and specifying specifying a lambda that will return the HTML string to output.

The column definitions are almost identical identical.

Paging support

Unlike its predecessor, the new grid does not have any logic for dealing with paging. This has all been moved to a separate Pager component. The old grid rendered the pager in its footer, while with the new grid you'd need to write your page like this:

<%= Html.Grid(Model.People).Columns(column => {
     		column.For(x => x.Id).Named("Person ID");
     		column.For(x => x.Name);
     		column.For(x => x.DateOfBirth).Format("{0:d}");
}) %>
 
<%= Html.Pager(Model.People) %>

Where's the code?

The code for the new grid is not in the mvccontrib release, so if you want to play with it you'll need to download and build the source. Alternatively, I've put together a custom build that can be downloaded here for the subversion-impaired.

In my next post, I'll be focussing on extending the grid by using GridModels and GridRenderers.

Written on February 22, 2009