If you searching the internet for jqGrid and ASP.NET MVC you will find many examples,
but all of them always define the jqGrid columns – see for an example the blog post from Phil Haack.
If you have a lot of jqGrids in your project you don’t want to define every single column for all the grids.

<script type="text/javascript">
    jQuery(document).ready(function () {

            url: '/Home/GridData/',
            datatype: 'json',
            mtype: 'GET',

            colNames: ['Id', 'Votes', 'Title'],
            colModel: [
          { name: 'Id', index: 'Id', width: 40, align: 'left' },

          { name: 'Votes', index: 'Votes', width: 40, align: 'left' },

          { name: 'Title', index: 'Title', width: 200, align: 'left'}],

            pager: jQuery('#pager'),
            rowNum: 10,
            rowList: [5, 10, 20, 50],

            sortname: 'Id',
            sortorder: "desc",
            viewrecords: true,

            imgpath: '/scripts/themes/coffee/images',
            caption: 'My first grid'


So I came up with the idea, why not just pass the data model class and let the grid create itself based
on the model!

So here is my solution.

First of all I wanted an easy syntax to create the Grid – for that reason I created a HtmlHelper extension
which takes the data model class.

    public static Grid<T> Grid<T>(this HtmlHelper htmlHelper, string name)
     where T : class {

      return new Grid<T>(name, htmlHelper.ViewContext.Writer);

Now you can create a grid simple like in the following example:


Looks nice or? So what about the ajax data?

The data has to come as a JsonResult – for that I created a GridExtension where you pass the data
and the information for sorting and paging.

So the only thing you have to call in the controller is the extension method AsJqGridResult.

Here is an example:

public ActionResult DynamicGridData(string sidx, string sord,
                                    int page, int rows){

      var context = new HaackOverflowDataContext();
      return (context.Questions.AsQueryable()
                     .AsJqGridResult(sidx, sord, page, rows));


Every time you change the DataModel it will create the columns based on it and you
don’t have to change the jqGrid column definitions.

One of the next steps to make everything even better would be to create DataViewModel classes
where you can define the ModelMetadata so that you have more control over which columns you
want to show and to have nice column names. – You can see this is in my second post.

If you are interested in the code or want to use it – here is the source code.