.NET Development Examined

MVC and DataTables

Sunday, November 20, 2011

One of the first things that Web Forms developers notice when starting to use MVC is the Model View Controller paradigm. The second thing (followed by a high shrill screech) is the absence of Controls. Followed by the incredulous question ‘what do you mean there is no GridView?’ I have to admit when I first started looking at MVC this bothered me a bit as well. Using a @foreach loop to build an HTML table gave me flashbacks to Classic ASP development. Eventually I accepted it as just another way that MVC departed from the Web Form way of development.

As I continue to explore MVC and its capabilities I am constantly impressed with how flexible MVC really is. In my exploration of the MVC ethos I have come across a couple gems, the jQuery DataTables plug-in and T4 Templates. I wondered why someone hadn’t created a T4 template using a jQuery table, and further thought that a well implemented T4 Template using DataTables might be a good rebuttal to the no GridView ‘problem’.

Covering this will take several posts, in the first one we will get DataTables hooked in our view. Then we will explore some T4 templating to easily implement our custom view.

So if you are interested read on…

Create a new MVC 3 project using the HTML5 sematic markup. Since we are going to be displaying a table we will need some data. For the basic implementation we will create a simple class, called SampleEmployee. So in your model folder add a class called SampleEmployee.cs and add a few properties:

public class SampleEmployee { public string Name { get; set; } public string Email { get; set; } public string Phone { get; set; } }

Now that we have our data structure we need to populate it with some sample data. For the basic sample we will use 15 or so records, to do this in your HomeController’s Index action add the following code:

List employees = new List(); for (int x = 0; x < 15; x++) { employees.Add(new SampleEmployee { Name = "Tom " + x, Email = "tom" + x + "@nowhere.com", Phone = "999-999-" + x.ToString().PadLeft(4,'9') }); } return View(employees.ToList());

With the data population task out of the way we need to display it in our view. Open the Index.cshtml of the Home view. We want this to be a strongly type view, so add the @model tag at the top of the page (make sure to use your projects namespace, mine was called Datatables):

@model List

Create a standard loop to build the table:

<table id="example"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Phone</th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Email) </td> <td> @Html.DisplayFor(modelItem => item.Phone) </td> </tr> } </tbody> </table>

It’s worth noting that Datatables expects to see a valid, fully defined table structure. This means you must include the <thead> and <tbody> sections.

Run your project now, you should see a simple HTML table with a lot of Toms. No big deal here, we have all see tables built like this. Let’s see how Datatables can help.

Download at http://www.datatables.net/ and extract the ZIP contents to a temporary location. We are interested in the files located in the ‘media’ folder. Add the files in the js, css, and images folder to your project.

Once imported open the demo_table.css file and adjust the image links to match your project locations.

Since we are using Datatables everywhere in this project add the .css and .js references to the _Layout.cshtml file. Make sure the dataTables.min.js file is loaded after the jQuery reference.

<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/demo_table.css")" rel="stylesheet" type="text/css" /> <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.dataTables.min.js")" type="text/javascript"></script> @RenderSection("top", false )

While still in the layout file add the @RenderSection as show above. This will allow us to inject content from our pages into the <head> tag of the page. I also like to put a @RenderSection(“bottom”,false) at the end of the page for script injection a the bottom of the page. The false tells MVC that the section is option. If the flag is set to true, or left out MVC will require that the render section be present on all pages.

We are ready to use DataTables now, so back in our Index.cshtml page add a render section for the top:

@section top{ <script type="text/javascript" charset="utf-8"> $(document).ready(function () { /* Init the table */ oTable = $('#example').dataTable({ "sScrollY": '100%' }); $(window).bind('resize', function () { oTable.fnAdjustColumnSizing(); }); }); </script> }

This is pretty basic jQuery magic here. Once the document is ready we are using the jQuery ID selector to find the element called “example”. You should note that we gave the <table> this same ID. Datatables finds this element and replaces it based on the definition in the Datatables JavaScript.

The $(window).bind statement is there to trigger a resizing of the column headers should the use change the page width. Without this statement the body of the table will resize, but the headers will not.

Running the page now should result in a paged, sortable, and filterable table. Datatables provides all these features with no effort on your part. Pretty sweet hun?

Next- AJAX!


Add Comment