Using MvcContrib GridModel classes to neaten views up
2010/01/01
Tags:
I can’t be the only person who thinks that views in Mvc get way too messy way too easily – especially when grids start taking over the world. Take this as an example:
= Html.Grid(Model.Merchants)
.Columns(column => {
column.For(x => Html.ActionLink("Select", "Details", new { id = x.MerchantId })).Named(String.Empty);
column.For(x => x.Name).Named("Name");
})
This is such a simple grid, but the view looks messy already.
MvcContrib exposes the Grid helper method from the MvcContrib.UI.Grid namespace. The grid builds columns using the lovely syntax shown above… but there is an alternative:
Custom GridModel classes
The Grid helper exposes another extension method called WithModel which accepts a GridModel class which we can use in our grids. If we create one for the grid above it looks like this:
public class MerchantIndexGridModel : GridModel<merchant>
{
public MerchantIndexGridModel(HtmlHelper html)
{
Column.For(x => html.ActionLink("Select", "Details", new { id = x.MerchantId })).Named(string.Empty);
Column.For(x => x.Name);
}
}
Which we then use in our view like this:
<%= Html.Grid(Model.Merchants).WithModel(new MerchantIndexGridModel(Html)) %>
Much cleaner. I like it.
No comments have been posted yet