Introducing the Smart Grid for ASP.NET MVC

Edit: Some documentation for the Grid is now available at the MvcContrib Wiki.

I've recently been working on an equivalent of the ASP.NET GridView for use with ASP.NET MVC.

This is partially inspired by the SmartGrid component which is part of the Castle Contrib project, but uses lambdas in order to build up a set of columns that can be automatically turned into an HTML table. For example, I might have this in an ASP.NET MVC Controller:

public class HomeController {
	private UserRepository repository = new UserRepository();

	public ActionResult Index() {
		ViewData["users"] = repository.FindAll();
		return RenderView();
	}
}

Then in my View I could have this:

<%
Html.Grid<Person>(
	"people",
	column => {
		column.For(p => p.Id);
		column.For(p => p.Name);
		column.For(p => p.Gender);
		column.For(p => p.RoleId);
	}
);
%>

Which would create something like this:

grid1

Note how the column names are automatically generated from the lambda expressions. However, you can override a column heading:

column.For(p => p.Id, "ID Number");

You can also create custom columns using lambda statements...

column.For("Custom Column").Do(p => { %>
	<td>A custom column...</td>
<% });

...and columns can have formatting applied to them:

column.For(p => p.DateOfBirth).Formatted("{0:d}");

Pagination is also fully supported by using the AsPagination extension method which works on any IEnumerable<T> or IQueryable<T>

public ActionResult Index(int? page) {
	ViewData["users"] = repository.FindAll().AsPagination(page ?? 1);
	return RenderView();
}

Which would produce something like this:

grid2

The source code is available in the mvccontrib trunk.

Written on May 21, 2008