jqGrid使用筆記.

wangsen2235068發表於2013-09-03

一.基本使用:

1)放置表格和分頁的html。

 <table id="search_member_table">
            </table>
            <div id="pager1"></div>
2) 在頁面載入完成後,呼叫繫結jqGrid表格程式碼.

function BindGrid(requestUrl) {
            $("#search_member_table").jqGrid({
                url: requestUrl,
                datatype: "json",
                cache: false,
                mtype: "GET",
                colNames: ["GMPI", "Last Name", "First Name", "MI", "Birth Date", "MemberID", "Market", "Eligible", "MemberId"],
                colModel: [
                    { name: 'GMPI', index: "GMPI" },
                    { name: 'LastName', index: "LastName" },
                    { name: 'FirstName', index: "FirstName" },
                    { name: 'MiddleName', index: "MiddleName", align: "center" },
                    { name: 'Birthdate', index: "Birthdate", datefmt: 'MM/dd/yyyy', align: "center" },
                    { name: 'MemberEligibility.MemberInsuranceCompany.CompanyId', index: "MemberEligibility.MemberInsuranceCompany.CompanyId" },
                    { name: 'Market.Market', index: "Market.Market" },
                    { name: 'MemberEligibility.IsEligibility', index: "MemberEligibility.IsEligibility", formatter: customFmatter, align: "center" },
                    { name: "MemberId", index: "MemberId", hidden: true }
                ],
                rowNum: 10,
                autowidth: true,
                height: "100%",
                rowList: [5, 10, 25, 50, 100, 9999],
                pager: jQuery('#pager1'),
                sortname: "DateUsed", //default primary key id
                sortorder: "desc",
                loadonce: false,
                viewrecords: true, //default false,number of pages and records are hidden, set true to show
                jsonReader: {
                    root: "Records", //Get json array data's root property
                    page: "PageIndex", //current page
                    total: "PageCount", //total page count
                    records: "RecordCount", //total records count
                    repeatitems: false, //if format like rows : [ [id:"1", cell:["cell11", "cell12", "cell13"]],...],need set true
                    cell: "", //defualt "cell",key:value's format set ""
                    id: "MemberEligibility.EligibilityId"//primary key
                }
            }).navGrid('#pager1', { edit: false, add: false, del: false });
        }


3)colModel中格式表格資料顯示的值. 

a.內建時間格式轉換: datefmt: 'MM/dd/yyyy'

b.formatter屬性設定一個自定義函式轉換:

    function customFmatter(cellvalue, options, rowObject){    
        return cellvalue == true ? "Y" : "N";
    }


二:高階篇:

1).行點選事件,onSelectRow放置在$("#search_member_table").jqGrid({});屬性中。

要點:

a. 獲取行物件$("#search_member_table").jqGrid("getRowData", id);   

b.獲取行物件的值,物件巢狀的話,用陣列形式作為索引:jsonObj["MemberEligibility.MemberInsuranceCompany.CompanyId"] };

 onSelectRow: function (id) {
                    var jsonObj = $("#search_member_table").jqGrid("getRowData", id);
                    if (jsonObj != null) {
                        var postdatas = { "mbrEligKey": id, "GMPI": jsonObj.GMPI, "LastName": jsonObj.LastName, "FirstName": jsonObj.FirstName, "MiddleName": jsonObj.MiddleName, "MemberId": jsonObj.MemberId, "Birthdate": jsonObj.Birthdate, "InsuranceCompanyId": jsonObj["MemberEligibility.MemberInsuranceCompany.CompanyId"] };
                        SaveSelectedMember(postdatas);
                    }
                },

2) 行中設定某一列,點選事件;新增 編輯、刪除等操作列 ,在gridComplete物件中設定:

//bind Role
    function BindNewsGrid(requestUrl) {
        $("#tbl_grid").jqGrid({
            url: requestUrl,
            datatype: "json",
            mtype: "GET",
            colNames: ["RoleId", "Role Name", "Role Desc", "Role Code", "Delete", "Edit", "Assign Menu"],
            colModel: [
                { name: 'RoleId', index: "RoleId", width: 50, hidden: true },
                { name: 'RoleName', index: "RoleName" },
                { name: 'RoleDesc', index: "RoleDesc", width: 250 },
                { name: 'RoleCode', index: "RoleCode" },
                { name: 'Delete', index: 'RoleId', align: 'center', sortable: false, width: 60 },
                { name: 'Edit', index: 'RoleId', align: "center", sortable: false, width: 60 },
                { name: "AssignMenu", index: "AssignMenu", align: "center", width: 60 },
            ],
            gridComplete: function () {
                var ids = jQuery("#tbl_grid").jqGrid('getDataIDs');
                for (var i = 0; i < ids.length; i++) {
                    var id = ids[i];
                    var del = "<img src='/Images/icon_news_del.png' onclick='deleteRole(" + id + ")' style='cursor:pointer' title='' /> ";
                    var edit = "<img src='/Images/icon_news_edit.png' onclick='editRole(" + id + ")' style='cursor:pointer' title='' /> ";
                    var assignMenu = "<img src='/Images/icon_roleedit.png' onclick='assignMenu(\"" + id + "\")' style='cursor:pointer' title='' /> ";
                    //don't allow assign when med info role.
                    var jsonObj = $("#tbl_grid").jqGrid("getRowData", id);
                    if (jsonObj != null && jsonObj.RoleCode == "MI") {
                        assignMenu = "";
                    }
                    $("#tbl_grid").jqGrid('setRowData', ids[i], { Delete: del, Edit: edit, AssignMenu: assignMenu });
                }
            },
            rowNum: 20,
            height: "100%",
            width: "975",
            rowList: [5, 10, 15, 20],
            pager: jQuery('#pager1'),
            sortname: "RoleId", //default primary key id
            loadonce: false,
            viewrecords: true, //default false,number of pages and records are hidden, set true to show
            jsonReader: {
                root: "Records", //Get json array data's root property
                page: "PageIndex", //current page
                total: "PageCount", //total page count
                records: "RecordCount", //total records count
                repeatitems: false, //if format like rows : [ [id:"1", cell:["cell11", "cell12", "cell13"]],...],need set true
                cell: "", //defualt "cell",key:value's format set ""
                id: "RoleId"//primary key
            }
        }).navGrid('#pager1', { edit: false, add: false, del: false });
    }

    function deleteRole(id) {
        if (!confirm("Are you sure to delete?")) {
            return;
        }
        $.ajax({
            url: '@Url.Action("DeleteRoleById")/?RoleId=' + id,
            success: function () {
                reloadGrid();
            }
        });
    }

    function editRole(id) {
        ShowAddEdit();
        $("#divAddEdit").html("<img src='/images/loading_circle.gif' />");
        $("#divAddEdit").load("/Admin/UpdateRole?RoleId=" + id + "&refresh=" + new Date().getTime() + "");
    }

3)重新整理grid資料:

 function reloadGrid() {
        var reqURL = "/Admin/GetRoleList";
        jQuery("#tbl_grid").jqGrid('setGridParam', { url: reqURL }).trigger("reloadGrid");
    }