简体   繁体   中英

How to achieve Paging in jqgrid

I am new to jquery and jqgrid. Can you help me understand and implement paging in the jqgrid with an example. Below is the code written so far. I have all the options set (pager, rowNum,rowList,loadonce: true)

    <html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
     <script src="Scripts/jquery.js" type="text/javascript"></script>

    <script src="Scripts/jquery-1.11.0.js" type="text/javascript"></script>

    <script src="Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>

    <link href="Scripts/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />

    <script src="Scripts/jquery-ui.js" type="text/javascript"></script>

    <!-- The jQuery UI theme extension jqGrid needs -->
    <link href="Scripts/ui.jqgrid.css" rel="stylesheet" type="text/css" />
    <script language="javascript" type="text/javascript">
                $(document).ready(function() {                
                LoadEmployees();
                });

                var ChargeItems = [];
                var NewBatchItems = [];
                function LoadEmployees() {
                    debugger;
                    $("#grps").jqGrid("clearGridData", true);
                    $("#grps").GridUnload();
                    $('#grps').jqGrid({
                        datatype: function() {
                            debugger;
                            jQuery.ajax({
                                type: 'POST',
                                contentType: 'application/json;charset=utf-8',
                                datatype: 'json',
                                data: {},
                                url: 'JQueryGridExample2.aspx/GetEmployees',
                                success: function(responseData) {
                                    debugger;
                                    ChargeItems = [];
                                    var NewBatchItems = JSON.parse(responseData.d);
                                    for (var i = 0; i < NewBatchItems.length; i++) {
                                        var item = NewBatchItems[i];
                                        ChargeItems.push({ "EmployeeID": item.EmployeeID, "EmployeeName": item.EmployeeName, "DepartmentName": item.DepartmentName, "DesignationName": item.Designation, "Salary": item.Salary });
                                    }
                                    debugger;
                                    var grid = $("#grps")[0];
                                    grid.addJSONData(ChargeItems);
                                },
                                error: function() {
                                    alert("Error with AJAX callback");
                                }

                            });
                        },

                        colNames: ['EmployeeID', 'EmployeeName', 'DepartmentName', 'Designation', 'Salary'],
                        colModel: [{ name: 'EmployeeID', index: 'EmployeeID', hidden: true, width: 100 }, { name: 'EmployeeName', index: 'EmployeeName', sortable: false, width: 250 }, { name: 'DepartmentName', sortable: false, index: 'Department', width: 250 }, { name: 'DesignationName', sortable: false, index: 'DesignationName', width: 250 }, { name: 'Salary', index: 'Salary', sortable: false, width: 100}],
                        height: "auto",
                        grouping: false,
                        refreshtext: "refresh",
                        MultiSelect: false,
                        pager: jQuery('#pager'),
                        rowNum: 5,
                        rowList: [5, 10, 15, 20, 30],
                        loadonce: true,
                        viewrecords: true,
                        recordtext: "View {0} - {1} of {2}",
                        emptyrecords: "No records to view",
                        loadtext: "Loading...",
                        pgtext : "Page {0} of {1}",
                        sortname: "EmployeeID",
                        sortorder: "asc",
                        jsonReader: {
                            repeatitems: false,
                            root: function(obj) { return obj; },
                            page: function(obj) { return $("#grps").jqGrid('getGridParam', 'page'); },
                            total: function(obj) { return Math.ceil(obj.length / $("#grps").jqGrid('getGridParam', 'rowNum')); },
                            records: function(obj) { return obj.length; }
                        },
                        caption: "Employee Details Report"
                    });
                    jQuery("#grps").jqGrid('navGrid', '#pager', { search: false, refresh: false, edit:false, add:false, del:false });


                }
                </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>

      <table id="grps" border="1"></table>
         <div id="pager"></div>
    </div>
    </form>
</body>
</html>



 [WebMethod]
        public static object GetEmployees()
        {
            List<EmployeeVo> objEmpList = new List<EmployeeVo>();
            EmployeeController objController = new EmployeeController();

            objEmpList = objController.GetEmployeesList();
            var jsonLabTests = (JsonConvert.SerializeObject(objEmpList));
            return jsonLabTests;
        }

1.Make your [WebMethod] like this:

[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public static List<EmployeeVo> GetEmployees()
{
    List<EmployeeVo> objEmpList = new List<EmployeeVo>();
    EmployeeController objController = new EmployeeController();

    objEmpList = objController.GetEmployeesList();
    return objEmpList;
}

2.Then just copy\\paste the code below over what you have:

<head runat="server">
    <title></title>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/redmond/jquery-ui.css" type="text/css" />
    <link href="https://cdn.jsdelivr.net/jqgrid/4.6.0/css/ui.jqgrid.css" rel="stylesheet" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqgrid/4.6.0/js/i18n/grid.locale-en.js"></script>
    <script src="https://cdn.jsdelivr.net/jqgrid/4.6.0/jquery.jqGrid.min.js"></script>

    <script type="text/javascript">
        $(function () {

            GetData();

            function GetData() {

                $('#grps').jqGrid({
                    url: 'JQueryGridExample2.aspx/GetEmployees',
                    mtype: 'POST',
                    ajaxGridOptions: { contentType: "application/json" },
                    datatype: "json",
                    serializeGridData: function (postData) {
                        return JSON.stringify(postData);
                    },
                    loadonce: true,
                    jsonReader: {
                        root: function (obj) { return obj.d; },
                        page: function (obj) { return 1; },
                        total: function (obj) { return 1; },
                        records: function (obj) { return obj.d.length; },
                        id: '0',
                        cell: '',
                        repeatitems: false
                    },
                    datatype: "json",
                    height: "auto",
                    pager: jQuery('#pager'),
                    rowNum: 5,
                    rowList: [5, 10, 15, 20, 30],
                    colNames: ['EmployeeID', 'EmployeeName', 'DepartmentName', 'Designation', 'Salary'],
                    colModel: [{ name: 'EmployeeID', index: 'EmployeeID', hidden: true, width: 100 }, { name: 'EmployeeName', index: 'EmployeeName', sortable: false, width: 250 }, { name: 'DepartmentName', sortable: false, index: 'Department', width: 250 }, { name: 'DesignationName', sortable: false, index: 'DesignationName', width: 250 }, { name: 'Salary', index: 'Salary', sortable: false, width: 100 }],
                    caption: "Employees table"
                });
                jQuery("#grps").jqGrid('navGrid', '#pager', { search: false, refresh: false, edit: false, add: false, del: false });
            }
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <table id="grps" border="1"></table>
        <div id="pager"></div>
    </form>
</body>

JavaScript

     function abc(){
            jQuery("#pnlGridData").jqGrid({
                datatype: function (postdata) {
                    params.PageSize = postdata.rows;
                    params.PageIndex = postdata.page;
                    $.ajax({
                        url: "abc.aspx/GetData",
                        data: JSON.stringify({ 'params': params }),
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function(jsondata){
 var thegrid = jQuery("#pnlGridData")[0];
    thegrid.addJSONData(JSON.parse(jsondata.d))
}
                        //failure: reportError
                    });
                },
                colNames: ['ID', 'Name'],
                colModel: [
                            { name: 'ProviderCredentials', index: 'ID', width: 35, align: 'center', sorttype: "int", sortable: false, resizable: false, hidden: true },
                            { name: 'ProviderCredentialsName', index: 'Name', width: 25, align: 'center', sorttype: "int", sortable: false, resizable: false },
                          ],
                rowNum: 5,
                rowList: [5, 10, 15, 20, 30],,        
                autoWidth: true,
                pager: "#JQGridData_Navigation",
                viewrecords: true,
                onPaging: function (pgButton) {
                    return Paging("pnlGridData", "JQGridData_Navigation", currentpageindex, pgButton);
                },

                rowNum: 0,
                editurl: "clientArray"

            });
        }

    function Paging(GridName, PagerControlName, LastVisitedPage, pgButton) {

        if (pgButton != "user") {
            PagerButton = pgButton.split('_');
            NavDirection = PagerButton[0];
        }
        else
            NavDirection = pgButton;

        var totalpages2 = parseInt(document.getElementById("sp_1_" + PagerControlName).innerHTML.replace(',', ''));


        if (NavDirection.toLowerCase() == "user") {
            var newpageindex2 = $("#pg_" + PagerControlName + " .ui-pg-input").val();

            if (isNaN(newpageindex2) || newpageindex2 < 1 || totalpages2 < newpageindex2) {
                alert("Invalid page number");
                $("#" + GridName).setGridParam({ page: LastVisitedPage });
                $("#pg_" + PagerControlName + " .ui-pg-input").val(LastVisitedPage);
                return 'stop';
            }
        }
    }

Html Code

        <table width="100%" align="center" id="trGrid" runat="server">
                                        <tr>
                                            <td></td>
                                        </tr>
                                        <tr>
                                            <td>
                                                <div id="divGridData" style="text-align:center; display: none;">
                                                    <table id="pnlGridData">
                                                    </table>
                                                    <div id="JQGridData_Navigation">
                                                    </div>
                                                </div>
                                                <div id="JQProviderCredentials_msgNoRecord" class="Emptry_Row_Gridview" style="display: none;">
                                                        No Record Found
                                                    </div>
                                            </td>
                                        </tr>
                                    </table>

Code Behind

          [WebMethod]
                public static string GetData(object params)
                {
                    try
                    {
                        int totalRecords = 0;
                        int PageSize = 0;
                        int totalpages = 0;
                        int PageIndex = 0;
                        Dictionary<string, object> paramsobject = (Dictionary<string, object>)params;
                        if (Convert.ToInt16(paramsobject["PageIndex"]) == 0)
                            PageIndex = 1;
                        else
                            PageIndex = Convert.ToInt16(paramsobject["PageIndex"]);
                        if (Convert.ToInt16(paramsobject["PageSize"]) == 0)
                            PageSize = 10;
                        else
                            PageSize = Convert.ToInt16(paramsobject["PageSize"]);
                        List<Dictionary<string, object>> lstData = new List<Dictionary<string, object>>();
                        var jsonSerializer = new JavaScriptSerializer();
                        DataSet objDataSet = new DataSet();

                        objDataSet =//get data

                        totalRecords = Convert.ToInt32(objDataSet.Tables[0].Rows[0]["TotalRowCount"].ToString());
                        totalpages = totalpages = (Convert.ToInt32(totalRecords) / Convert.ToInt32(PageSize)) + (Convert.ToInt32(totalRecords) % Convert.ToInt32(PageSize) > 0 ? 1 : 0);
                        lstData = GetTableRows(objDataSet.Tables[0]);
                        var data = new
                        {
                            total = totalpages,
                            page = PageIndex,
                            records = totalRecords,
                            rows = lstData
                        };
                        return jsonSerializer.Serialize(data);
                    }
                    catch (Exception ex)
                    {
                        ProcessException(ex, true);
                        throw;
                    }
                }                   


        public static List<Dictionary<string, object>> GetTableRows(DataTable dtData)
                {
                    List<Dictionary<string, object>>
                    lstRows = new List<Dictionary<string, object>>();
                    Dictionary<string, object> dictRow = null;

                    foreach (DataRow dr in dtData.Rows)
                    {
                        dictRow = new Dictionary<string, object>();
                        foreach (DataColumn col in dtData.Columns)
                        {
                            dictRow.Add(col.ColumnName, dr[col]);
                        }
                        lstRows.Add(dictRow);
                    }
                    return lstRows;
                }       

Now just need to do is add Pagesize and PageIndex to your Stored Proc. And get data between that.

You should never use datatype defined as function . You should use datatype: "json" instead and specify url: 'JQueryGridExample2.aspx/GetEmployees' and ajaxGridOptions: { contentType: "application/json" } (or ajaxGridOptions: { contentType: "application/json;charset=utf-8" } ) as the option of jqGrid. jqGrid will makes the corresponding Ajax request for you.

Additionally you should fix the code of the WebMethod and to return List<EmployeeVo> directly instead of calling JsonConvert.SerializeObject explicitly. It's important to understand that ASP.NET makes for you internally the serialization of returned data to JSON or to XML based on contentType of the request. In other words you should remove the lines var jsonLabTests = (JsonConvert.SerializeObject(objEmpList)); return jsonLabTests; var jsonLabTests = (JsonConvert.SerializeObject(objEmpList)); return jsonLabTests; forom your code and to use return objEmpList; instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM