Using jQGrid with ASP MVC controllers

April 24th, 2012 by admin Leave a reply »

I have been toying around with making the JQuery Grid found over on this site http://www.trirand.com/blog/ work with a asp.net controller and I finally got it working after much trials and tribulations, all because of a couple of little gotchas I either didn’t see in the documentation or just overlooked.

Here is the javascript code that will load a jQgrid into your div on your page that uses a plain ActionResult method in a MVC controller that is tagged with the [HttpPost] attribute.

$("#list2").jqGrid({
                url: '/Product/GetProducts',
                datatype: "json",
                jsonReader : { repeatitems: false },
                mtype: 'POST',
                width: 550,
                colNames: ['Name'],
                colModel: [{ name: 'Name', width: 120, align: 'left', editable: true}],
                toppager: true,
                pager: $("#jqTablePager"),
                rowNum: 10,
                rowList: [5, 10, 20, 50],
                sortorder: "desc",
                viewrecords: true,
                multiselect: true
            });

Notice this line ‘jsonReader : { repeatitems: false }’, you seem to need that line if you don’t have an Id column in your data that you are mapping to a column, that was really killing me cause I was just trying to show a simple list of products with a Name property in there.

The other ‘gotcha’ that I had to do a lot of research to finally find out was the way that you have to wrap your JSON in order for the grid to display it correctly. I have included the code below that will return a correct set of JSON assuming you are using a List of some kind of object.

var jsonData = new
            {
                total = products.Count(),
                page = totalPages,
                records = products.Count(),
                rows = (
                    from p in products
                    select new {
                        p.Name
                    }
                ).ToArray()
            };

And then finally here is the HTML that will place the jQgrid and a paging mechanism right below it.

<table id="list2"></table>
<div id="jqTablePager" />

Advertisement

Leave a Reply