How to use JqGrid with ASP.NET MVC

Step 1 : Download JqGrid plugin

You can do either of the following:

  1. Download the files from trirand.com.
  2. Use Nuget Package Manager to download the files for you.

I prefer using Nuget Package Manager to download and integrate any 3rd party plugins, it reduces time and is not error prone. Open the Nuget Package Manager by right clicking the Web Project and selecting the ‘Manage Nuget Package’ option. In search box type in ‘jquery.jqGrid’ and install it.

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Step 2 : Include the downloaded jqGrid css and js files in your view : Ideally I would be using a bundle for both css and js, but I for the sake of keeping it simple here is what I am doing…

<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 : JqGridObject class

JqGrid on every

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.

imge

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

About Yasser Shaikh

Hello, I am a Web Dev, employed with Media.Net where I primarily work on ASP.NET MVC and Angular JS based developement.

Questions? Enquiries? Comments? Or even just want to say “Hi” to me, you are welcome to all of that. Just drop me a message at “mail@yassershaikh.com” and I’ll get back to you as soon as possible.

Cheers !

10 comments

  1. 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.

    1. 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…

  2. 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.

  3. If I am Trying to add the code on as a question on stack overflow I am getting This Error ,How to formatting I am not Getting .SO What i Can Do For this [Your post appears to contain code that is not properly formatted as code. Please indent all code by 4 spaces using the code toolbar button or the CTRL+K keyboard shortcut. For more editing help, click the [?] toolbar icon.].Previous ,Newx Previos ,Last Those Buttons is Disabled,but how to enable those buttons .Please Help Me .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>