Note: This walkthrough is based on the 1.0 release of ASP.NET MVC, MvcContrib version 1.0.0.916 with a minor code change, jQuery 1.2.6 (included in the MVC release) and jQuery datatables 1.4.

Introduction

For the past few months (and 100+ volunteer hours!) I’ve been creating a web application for Hands on DC that calculates volunteers, gallons of paint, and materials for work projects for their annual Work-a-Thon event. After the encouragement of a few coworkers who did some initial work on the project, I committed to using ASP.NET MVC, technology which has been out over a year but just reached a production 1.0 release at Mix 09 this year.

Getting up and running with MVC wasn’t an easy task. The project was also my first foray into LINQ to SQL, and really .NET 3.5 in general, so it was a little intimidating at first! There’s not much documentation and it’s split across the many release versions of MVC. The main site will get you up doing very basic things (but is seriously lacking content), though Phil Haack’s webcast and Scott Hanselman, et. al.’s free e-Book are helpful.

In the process, I discovered some important companion pieces in MvcContrib and jQuery, including the validation plugin and the datatable plugin. I want to highlight work that I did to combine the MvcContrib data grid with the datatable for sorting, paging and filtering. This was something I struggled with for several hours, so I’m hoping there is some value in posting the full example.

projectsFigure 1. Example of using MvcContrib with jQuery datatable plugin.

Walkthrough

Here is a complete from-scratch example.

  • Create a new ASP.NET MVC Web Application. Press F5 to make sure it runs.
  • Drag and drop the “media” folder from the datatable project directory (where you unzipped the project) into the new Solution, like so:

datatable-media Figure 2. Solution after copying the datatable media folder.

  • Add a reference to the MvcContrib.dll.
  • Open the Views/Home/Index.aspx file and add the following under the page directive:
<%@ Import Namespace="MvcContrib.UI.Grid" %>
<%@ Import Namespace="MvcContrib.UI.Grid.ActionSyntax" %>
  • Open the Views/Shared/Site.Master file and add references to jquery, jquery.dataTables and the demos.css file, like so:
Hide Code [-]
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title>
<asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title> 
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" /> 
<link href="../../media/css/demos.css" rel="stylesheet" type="text/css" /> 
<script src="../../media/js/jquery.js" type="text/javascript"></script> 
<script src="../../media/js/jquery.dataTables.js" type="text/javascript"></script> 
</head>
{..} Click Show Code
  • Now set up some dummy data in the HomeController.cs file like so (add to the body of the class):
Hide Code [-]
public enum Medal
{
    Gold,
    Silver,
    Bronze
}

public class MedalWinner
{
    public string Location { get; set; }
    public string Year { get; set; }
    public string Sport { get; set; }
    public Medal Medal { get; set; }
    public string Country { get; set; }
    public string Name { get; set; }

    public MedalWinner(string l, string y, string s, Medal m, string c, string n)
    {
        Location = l;
        Year = y;
        Sport = s;
        Medal = m;
        Country = c;
        Name = n;
    }
}

public ActionResult Index()
{
    ViewData["Message"] = "Welcome to ASP.NET MVC!";

    var medalWinners = new List<MedalWinner>();
    medalWinners.Add(
        new MedalWinner("Athens", "2004", "Handball",
            Medal.Gold, "Croatia", "LOSERT, Veni"));
    medalWinners.Add(
        new MedalWinner("Athens", "2004", "Handball",
            Medal.Gold, "Croatia", "BALIC, Ivano"));
    medalWinners.Add(
        new MedalWinner("Athens", "2004", "Handball",
            Medal.Gold, "Croatia", "ZRNIC, Vedran"));
    medalWinners.Add(
        new MedalWinner("Athens", "2004", "Handball",
            Medal.Silver, "Germany", "JANSEN, Torsten"));
    medalWinners.Add(
        new MedalWinner("Athens", "2004", "Handball",
            Medal.Silver, "Germany", "KRETZSCHMAR, Stefan"));
    medalWinners.Add(
        new MedalWinner("Athens", "2004", "Handball",
            Medal.Silver, "Germany", "VON BEHREN, Frank "));

    ViewData["MedalWinners"] = medalWinners;

    return View();
}
{..} Click Show Code
  •   Now we have some data to work with. In the view (ViewData[“MedalWinners”]). Test that theory by adding the following code to the “indexContent” content block in Views/Home/Index.aspx:
Hide Code [-]
<ol>
<% foreach (HomeController.MedalWinner winner 
       in (List<HomeController.MedalWinner>)ViewData["MedalWinners"] )
{ %>
    <li><%= winner.Name %>, <%= winner.Country %></li>
<% } %>
</ol>
{..} Click Show Code
  • You should see output like this:

medalwinners1

  • Assuming that worked, we’re ready to do some grid work! Once you get the basic syntax, the MvcContrib grid makes display a cinch. This is the “action syntax” so make sure your imports are right (shown at the top of the walkthrough.
Hide Code [-]
<% Html.Grid((List<HomeController.MedalWinner>)ViewData["MedalWinners"])
       .Columns(column =>
       {
           column.For(c => c.Year);
           column.For(c => c.Location);
           column.For(c => c.Name);
           column.For(c => c.Country);
           column.For(c => c.Medal.ToString());
           column.For(c => c.Sport);
       }).Render();
%>
{..} Click Show Code
  • Run the application; you should see output like so:

    medalwinners2
  • That’s pretty easy, but not terribly useful yet. For fun, let’s add a Live search on the name field so we can see who these athletes are. The “Action Syntax” makes it simple to do powerful clean custom code for each cell. Pretty slick! Note that you need to specify the table cell tags or you’ll get messed up output.
Hide Code [-]
<% Html.Grid((List<HomeController.MedalWinner>)ViewData["MedalWinners"])
       .Columns(column =>
       {
           column.For(c => c.Year);
           column.For(c => c.Location);
           column.For(c => c.Name).Named("Athlete Name").Action(a => {%>
               <td><a href=
               "http://search.live.com/results.aspx?q=<%= HttpUtility.UrlEncode(a.Name) %>&form=QBLH">
               <%= HttpUtility.HtmlEncode(a.Name) %></a></td>
           <%
           });
           column.For(c => c.Country);
           column.For(c => c.Medal.ToString());
           column.For(c => c.Sport);
       }).Render();
%>
{..} Click Show Code
  • So now our output name is linked to a Live Search.
  • Now we’re ready to incorporate the jquery datatable stuff. If you see in the directory that you unzipped the datatable project to, there is an “eaxmple_zero_config.html” file. Let’s steal the code from the top of that.

    In order to get this to work, we need to add an id attribute to the grid, as is shown below.

    Let’s also style it a little by putting it in a container. Otherwise the search box doesn’t align with the table and looks a little wonky:
Hide Code [-]
<script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
        $('#example').dataTable();
    });
</script>

<style>
#example { width: 100%; }
#container { width: 600px; }
</style>
    
<div id="container">
<% Html.Grid((List<HomeController.MedalWinner>)ViewData["MedalWinners"])
       .Columns(column =>
       {
           column.For(c => c.Year);
           column.For(c => c.Location);
           column.For(c => c.Name).Named("Athlete Name").Action(a => {%>
               <td><a href=
               "http://search.live.com/results.aspx?q=<%= HttpUtility.UrlEncode(a.Name) %>&form=QBLH">
               <%= HttpUtility.HtmlEncode(a.Name) %></a></td>
           <%
           });
           column.For(c => c.Country);
           column.For(c => c.Medal.ToString());
           column.For(c => c.Sport);
       }).Attributes(id => "example").Render();
%>
</div>
{..} Click Show Code
  • Now we can do sorting by clicking the column names, filtering by entering text in the search box, and pagination by selecting the drop-down for “show X entries”.

medalwinners3

  • That’s pretty much it! Before we part, let’s make a quick foray into the syntax of making changes to the datatable initialization code. We can disable columns so they can’t be sorted, create a custom sort order, and change the default length by setting some properties. Let’s disable sorting by the first and sixth columns, sort by name by default, and set the default paging to 25. Just change the javascript block to this:
Hide Code [-]
$(document).ready(function() {
    $('#example').dataTable({
        "iDisplayLength": 25,
        "aaSorting": [[2, "asc"]],
        "aoColumns": [{ "bSortable": false }, null,
            null, null, null, { "bSortable": false}]
    });
});
{..} Click Show Code
  • And voilá!

medalwinners4

[Download complete source code] (394KB, ZIP file)