Walkthrough: full example of using MvcContrib grid with jQuery datatable


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)

Comments (24)

  1. Thank you for submitting this cool story – Trackback from DotNetShoutout

  2. You’ve been kicked (a good thing) – Trackback from DotNetKicks.com

  3. defeated says:

    ASP.NET MVC 1.0 comes with jQuery 1.3.2, I’m curious why you chose version 1.2.6 instead?

  4. paulwhit says:

    @defeated I started the project with a beta version, so I guess it was a remnant of that. It probably doesn’t matter 🙂 thanks for the comment

  5. Zunanji viri says:

    Development ASP.NET MVC Training Kit Full example of using MvcContrib grid with jQuery datatable – Excellent

  6. goldytech says:

    The solution dosent work when I deployed on IIS 7.

    It gave me javascript error. I can only see a normal grid without search,sorting and pagination features.

    Webpage error details

    User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; GTB6; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.5.21022; .NET CLR 3.5.30729; OfficeLiveConnector.1.3; OfficeLivePatch.1.3; .NET CLR 3.0.30729)

    Timestamp: Sun, 31 May 2009 15:46:46 UTC

    Message: Object expected

    Line: 42

    Char: 1

    Code: 0

    URI: http://localhost/GridTest

    Is something wrong in configuration ??

    Please advise.

  7. sclog2003 says:

    Excellent article, but found a another one with the simpler approach.

    http://arahuman.blogspot.com/2009/06/jqgrid-using-mvc-json-and-datatable.html

  8. mahingupta says:

    Download link is not working. But walk through is so detailed I managed to build one myself. Thanks for sharing.

  9. TamDuong says:

    Source code is not available, can you upload it again !  

  10. TamDuong says:

    How can it CRUD database form sql server? Thank you

  11. Usman Shabbir says:

    hi i have also used jQuery Datatable with ASP.net in C# the details can be found over

    usmanshabbir.blogspot.com/…/simplest-way-to-use-jquery-datatable-in.html

  12. Ashwin says:

    Exactly what I was looking for. Thanks!

  13. Frank says:

    Cool, but what if you had a search form and a  grid on the same page? The sort links in the grid always want to use the same action as the form. There doesn't seem to be any way to tell the grid to do otherwise. Does this mean that the grid must always have its own controller?

  14. Usman Shabbir says:

    If some one is interested in looking jQuery Data table with custom pagination and server side processing from simple ASP.net Application then can view an article

    usmanshabbir.blogspot.com/…/extending-jquery-datatable-with-server.html

  15. Max says:

    Source code is unavailable. Is it possible to either upload it again. Or Email it to me?

  16. Niraj says:

    Hi Max,

    its easy to use, once you have your controler returning viewmodel.

    <code>

    public ActionResult salesreport()

           {

               handsetviewmodel vm = new handsetviewmodel();

               return View(vm);

           }

    </code>

    you can write following code to display a simple grid

    <code>

    <%: Html.Grid(Model.handsetstock()).Columns(column => {

                   column.For(c=>c.itemcode);

                   column.For(c => c.imeicsv);

               })%>

    </code>

  17. ChelseaJcole says:

    Source code is unavailable. Is it possible to either upload it again. Or Email it to me?

  18. Babiloba says:

    This was Amazing!! So easy and still so powerfull!

    Thanks

  19. TFM says:

    It looks like your source control link goes to a personal website instead of the source control.

  20. sample code link is broken……..please check & update

  21. Classie says:

    Hi, this is an awesome example and I thank you. The only thing is your download link says it is not available. Thanks

  22. Caroline says:

    How to fix the header ? Like the freeze first row option in MS Excel

  23. Mohammad Ali says:

    how to hosting in data base in sql 2008 plz any bay help me I am Very Sad dont s hosing