Creating a grid of data is a common task when building a dynamic website.  I recently started looking for a good grid component that would play nice with both JQuery and ASP.NET MVC.  The solution I ended up with is jqGrid.    I’m going to walk through a simple example of setting up a grid and populating it via JSON with an MVC controller.  I’ll also show how to add, edit and delete rows to the grid.

Setup

First, I created a simple User table and generated my Linq to SQL classes.  I just want to show a simple grid of users, showing ID, First Name, Last Name, Email address and Birthday.  When we are done, the finished grid will look something like this:

grid

One thing that I like about this grid is that it supports jQuery UI right out of the box.  After downloading jQuery UI and jqGrid and following the installation instructions, just reference the relevent .css and .js files to get started, which I did in a master page:

<link href="../../Content/jquery-ui-1.8.custom.css" rel="Stylesheet" type="text/css" />
<link href="../../Content/ui.jqgrid.css" rel="Stylesheet" type="text/css" />
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.custom.min.js" type="text/javascript" ></script>
<script src="../../Scripts/grid.locale-en.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="../../Scripts/grid.custom.js" type="text/javascript"></script>

HTML

The first thing I want to do is set up my grid on the client site.  This requires two parts.  The first is the HTML landing spot for the grid, pager and search box, which looks like this:

<div id="search"></div>
<table id="grid" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>

Javascript 


The next part is the Javascript that takes care of configuring our grid and hooking it up to the HTML elements on the page.

    $(document).ready(function() {
        jQuery("#grid").jqGrid({
            url: '/Home/SampleGridData/',
            datatype: 'json',
            mtype: 'POST',
            colNames: ['Id', 'First Name', 'Last Name', 'Email', 'Birthday