How to use JqGrid with ASP.NET MVC

Step 1 : Download JqGrid jquery plugin

There are two ways you can do this.

1. You can download the plugin from trirand.com.

2. Or you can download and install using the Nuget Package Manager.

I personally prefer using Nuget Package Manager to download and install any plugin. Simply search for “jquery.JqGrid” and click “install”. Below is screenshot by screenshot example on how to install.

Step 2 : Include these css and js files in your view

<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />  
<link href="../../Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" type="text/css" />  
<link href="../../Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />

<script src="../../Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>  
<script src="../../Scripts/i18n/grid.locale-en.js" type="text/javascript"></script>  
<script src="../../Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>  

Step 3 : Prepare a JqGridObject Class

If you have worked with JqGrid before you will no doubt be familiar with the default parameters passed to any ajax request: “page”, “rows”, “sidx” & “sord”. These parameters correspond to current page, records per page, sort column, and sort order respectively.

The screenshot below, will help you understand this better.

So, to handle this I have prepared a class called ‘JqGridObject’.

public class JqGridObject  
{  
public string Page { get; set; }  
public int PageSize { get; set; }  
public string SortColumn { get; set; }  
public string SortOrder { get; set; }  
public List<Fruit> Data { get; set; }  
}

public class Fruit  
{  
public int Id { get; set; }  
public string Name { get; set; }  
} 

Step 4 : Send json data from controller using this JqGridObject class

public ActionResult GetJqGridData(string page, string rows, string sidx, string sord)  
{  
var jqGridData = new JqGridObject()  
{  
Data = GetSomeSampleData(),  
Page = page,  
PageSize = 3, // u can change this !  
SortColumn = sidx,  
SortOrder = sord  
};

return Json(jqGridData, JsonRequestBehavior.AllowGet);  
}

public List<Fruit> GetSomeSampleData()  
{  
return new List<Fruit>  
{  
new Fruit{Id = 1, Name = "Apple" },  
new Fruit{Id = 2, Name = "Melon" },  
new Fruit{Id = 3, Name = "Orange" },  
new Fruit{Id = 4, Name = "Grapes" },  
new Fruit{Id = 5, Name = "Pineapple" },  
new Fruit{Id = 6, Name = "Mango" },  
new Fruit{Id = 7, Name = "Bannana" },  
new Fruit{Id = 8, Name = "Cherry" }  
};  
}  

Step 5: Final Step :- JqGrid jquery call.

<script type="text/javascript">  
$(document).ready(function() {  
$("#myGrid").jqGrid({  
url:'@Url.Action("GetJqGridData")',  
datatype:'json',  
myType:'GET',  
colNames:['Id', 'Name'],  
colModel:[  
{ name: 'Id', index: 'Id'},  
{ name: 'Name', index: 'Name'}  
],  
jsonReader: {  
root: 'Data',  
id: 'id',  
repeatitems: false  
},  
pager: $('#myPager'),  
rowNum:5,  
rowList: [2, 5, 10],  
width:600,  
viewrecords:true,  
caption: 'Jqgrid MVC Tutorial'  
});  
});  
</script>

<table id="myGrid"></table>  
<div id="myPager"></div>  

and our jqgrid is ready to serve !

Hope you found this useful :)

More Links

http://haacked.com/archive/2009/04/13/using-jquery-grid-with-asp.net-mvc.aspx

http://bartreyserhove.blogspot.in/2008/08/aspnet-mvc-and-jqgrid.html

  • prasath

    please explain this project

  • Vaibhav Shah

    nicely explained

  • Bhargav Reddy

    Same Thing I Implemented .Its Woring Fine ,Previous ,Newx Previos ,Last Those Buttons is Disabled,but how to enable those buttons .I tried but i am not getting those buttons .So I am new to JQGrid.Please Help Me.

    • yassershaikh

      The buttons are normally disabled if the number of records are equal to or less than the page size, in that case the pager is not required and hence is disabled by default. In case you have a different problem pls post your question on http://stackoverflow.com/questions/ask and share the link here…

  • Bhargav Reddy

    This is my View code.

    var lastsel = 0;

    $(document).ready(function () {

    var Caption;

    Caption = “List of Ware Houses”;

    // $(‘#gs_act’).attr(“disabled”, true);

    var $grid = $(“#myGrid”), pagerDiv = “#myPager”;

    $(“#myGrid”).jqGrid({

    url: ‘@Url.Action(“GetJqGridData”, “CommonPaging”)’,

    datatype: ‘json’,

    myType: ‘POST’,

    colNames: ['Actions', 'Id', 'ParentId', 'Name', 'Code', 'Parent Name'],

    colModel: [

    { name: 'act', index: 'act', sortable: false, width: 40, align: 'center' },

    { name: 'Id', index: 'Id', sorttype: "uniqueId", hidden: true, editrules: { edithidden: false } },

    { name: 'ParentId', index: 'ParentId', sorttype: "uniqueId", hidden: true, editrules: { edithidden: false } },

    { name: 'Name', index: 'Name', sorttype: "string", editable: true, align: 'center', NullIfEmpty: true, editrules: { required: true } },

    { name: 'Code', index: 'Code', editable: true, align: 'center', NullIfEmpty: true },

    { name: 'ParentName', index: 'ParentName', editable: true, align: 'center', NullIfEmpty: true },

    ],

    jsonReader: {

    repeatitems: false,

    root: ‘Data’,

    page: ‘GridData.Page’,

    total: ‘GridData.TotalPages’,

    records: ‘GridData.RecordCount’,

    userdata: ‘GridData.FooterTotals’,

    id: ‘Id’,

    },

    //pager: $(‘#myPager’),

    pager: pagerDiv,

    rowNum: 5,

    rowList: [2, 5, 10, 15, 20, 25, 30],

    width: 600,

    viewrecords: true,

    sortorder: “desc”,

    sortname: ‘Name’,

    caption: Caption,

    loadOnce: true,

    emptyDataText: ‘There are no records.’,

    gridComplete: function () {

    var ids = jQuery(“#myGrid”).jqGrid(‘getDataIDs’);

    for (var i = 0; i < ids.length; i++) {

    var cl = ids[i];

    // be = "”;

    be = “”;

    //se = “”;

    //ce = “”;

    de = “”;

    // ,{successfunc: function( response ) {ForErrormsgs(response);}});

    jQuery(“#myGrid”).jqGrid(‘setRowData’, ids[i], { act: be + ‘ ‘ + de });

    }

    },

    editurl: ‘@Url.Action(“Create”, “JqGridWithPaging”)’,

    //scroll: true,

    //gridview: true,

    autowidth: true,

    rownumbers: true,

    //imgpath: ‘/scripts/themes/basic/images’,

    });

    $grid.jqGrid(‘navGrid’, pagerDiv, { refresh: false, edit: false, add: false, del: false, search: false, select: false });

    $grid.jqGrid(

    ‘navButtonAdd’,

    pagerDiv,

    {

    caption: “”,

    buttonicon: “ui-icon-refresh”,

    title: $.jgrid.nav.refreshtitle,

    onClickButton: function () {

    $(this).jqGrid(‘setGridParam’, { datatype: ‘json’ });

    // $(this).trigger(‘reloadGrid’, [{ page: 1 }]);

    }

    }

    );

    $grid.jqGrid(‘filterToolbar’, {

    stringResult: true,

    searchOnEnter: false,

    defaultSearch: ‘cn’,

    beforeSearch: function () {

    var postedData = {};

    postedData = $(this).jqGrid(‘getGridParam’, ‘postData’);

    // g.claims.FilterPageSort(postedData);

    return false;

    }

    });

    });

    function editRowFunc(cl) {

    // jQuery(‘#myGrid’).editRow(cl);

    $.get(‘/WareHouse/Edit’, { Id: cl }, function (data) {

    $(“#Name1″).val(”);

    $(“#Code1″).val(”);

    $(“#ParentName1″).val(”);

    $(“#divSuccessErrorMsg”).hide();

    $(“#divFailedErrorMsg”).hide();

    $(‘#divEdit’).html(”);

    $(‘#divEdit’).html(data);

    //$.post(‘/CommonPaging/Search’, { Name: $(“#Name1″).val(), Code: $(“#Code1″).val(), ParentName: $(“#ParentName1″).val() }, function (data) {

    // $(‘#divGrpView’).html(data);

    //});

    //if (cl !== undefined) {

    // //if (cl && cl !== lastsel) {

    // jQuery(‘#myGrid’).restoreRow(lastsel);

    // lastsel = cl;

    //}

    });

    }

    function deleteRowFunc(cl) {

    $.post(‘/WareHouse/Delete’, { Id: cl }, function (data) {

    if (data == “Deleted Successfully”) {

    DisplaySuccessErrorMessage(“divSuccessErrorMsg”, data);

    $(“#divSuccessErrorMsg”).show();

    $(“#FailedErrorMsg”).hide(); $(“#divFailedErrorMsg”).hide();

    jQuery(“#myGrid”).setGridParam({ rowNum: 5 }).trigger(“reloadGrid”);

    }

    else {

    var DBError = “DB Error”;

    DisplaySuccessErrorMessage(“divFailedErrorMsg”, DBError);

    $(“#divFailedErrorMsg”).show();

    }

    });

    }

    this is the controller action

    public ActionResult GetJqGridData(string page, string rows, string sidx, string sord, bool _search, string filters)

    {

    LocationForm locationForms = new LocationForm();

    string jsonString = filters; string Id = null;

    if (filters != null)

    {

    Filter filterList = JsonConvert.DeserializeObject(filters);

    foreach (var values in filterList.rules)

    {

    if (values.field == “Code”)

    {

    locationForms.Code = values.data;

    }

    if (values.field == “Name”)

    {

    locationForms.Name = values.data;

    }

    if (values.field == “ParentName”)

    {

    locationForms.ParentName = values.data;

    }

    }

    }

    var jqGridData = new JqGridObject()

    {

    Data = View(Id), PageSize = Conversion.ToInt32(rows),Page = Conversion.ToString(5),

    SortColumn = sidx,SortOrder = sord

    };

    return Json(jqGridData, JsonRequestBehavior.AllowGet);

    }

    public List View(string Id)

    { List areaForm = Show(Conversion.ToNullableGuid(Id)).View;

    return areaForm; }

    This the my Code .This Code Every thing Woring Fine Except Previous ,Next Previos ,Last buttons.Previous ,Next Previos ,Last Those Buttons is Disabled,but how to enable those buttons .I tried but i am not getting those buttons .I am new to JQGrid.Please Help Me anyone.This is urgent Requirement.

    • yassershaikh

      Please dont spam here… post this as a question on stackoverflow. Thanks.