繁体   English   中英

如何在jqgrid中实现分页

[英]How to achieve Paging in jqgrid

我是jquery和jqgrid的新手。 您能否通过示例帮助我理解并实现jqgrid中的分页。 下面是到目前为止编写的代码。 我有所有选项集(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.像这样制作你的[WebMethod]

[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;
}

然后只需复制\\粘贴下面的代码就可以了:

<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代码

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

代码背后

          [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;
                }       

现在只需要将PagesizePageIndex添加到您的存储过程中。 并获取数据。

永远不应该使用定义为函数的datatype 您应该使用datatype: "json"而是指定url: 'JQueryGridExample2.aspx/GetEmployees'ajaxGridOptions: { contentType: "application/json" } (或ajaxGridOptions: { contentType: "application/json;charset=utf-8" } )作为jqGrid的选项。 jqGrid将为您发出相应的Ajax请求。

此外,您应该修复WebMethod的代码并直接返回List<EmployeeVo> ,而不是显式调用JsonConvert.SerializeObject 重要的是要理解ASP.NET 内部为您提供返回数据到JSON或基于请求的contentType的XML的序列化。 换句话说,你应该删除行var jsonLabTests = (JsonConvert.SerializeObject(objEmpList)); return jsonLabTests; var jsonLabTests = (JsonConvert.SerializeObject(objEmpList)); return jsonLabTests; forom你的代码并使用return objEmpList; 代替。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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