In this recipe, we are going to tackle the usually quite complex task of displaying grid data for a collection of data objects. Rather than using a looping structure and manually configuring how the data should be displayed, we will instead use the MvcContrib
grid. This gets us close to the traditional style of the ASP.NET grid.
MvcContrib
and NBuilder. Models
directory called Product
. Then add the following properties to represent our product.Models/Product.cs:
public class Product { public Guid ProductID { get; set; } public string ProductName { get; set; } public double Price { get; set; } }
HomeController
called ListProducts
. This action will be responsible for creating a collection of products with NBuilder and returning that collection to the view.Controllers/HomeController.cs:
public ActionResult ListProducts() { List<Product> products = Builder<Product>.CreateListOfSize(10).Build().ToList(); return View(products); }
Product
. Then right-click on the new ListProducts
action and add a view. Make this a strongly typed empty view based on Product
. Change the Inherits
declaration to be a list of products rather than just a Product
. MvcContrib
. Do this by importing MvcContrib.UI.Grid
. Then drop a call to the grid.Views/Home/ListProducts.aspx:
...
<%@ Import Namespace="MvcContrib.UI.Grid" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
ListProducts
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>ListProducts</h2>
<%= Html.Grid(Model) %>
</asp:Content>
... <%= Html.Grid(Model).Columns (c=> { c.For(m => m.Price); c.For(m => m.ProductName); c.For(m => m.ProductID); } ) %> ...
Home/ListProducts
to see the new grid.
MvcContrib
extends an already robust framework with some great functionality. The Grid is no exception, simple but effective. The Grid extension helper iterates through a collection and outputs a table. What I really like a lot about this helper and the direction of .NET projects in general, is its fluent approach—the grid is created in the first method, and columns (using lambda expression) are applied in the second.