jqGrid 使用示例
JQGrid是一个在jquery基础上做的一个表格控件,纯粹做数据前台展示,数据源以ajax的方式和服务器端通信获取。
官方demo见http://trirand.com/blog/jqgrid/jqgrid.html,
api说明见http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs
下面是服务端返回json数据格式的示例:
1、jqGrid以loadonce=true的方式获取数据,数据从服务器只加载一次到前台,客户端自动分页,客户端分页参数不再回传到服务端的请求参数里面
客户端
先构造表格控件(最后两列添加自定义格式的列),
jQuery("#list").jqGrid(
{ datatype: "local", height: 'auto', autowidth: true, colNames: ['id', '车牌号码', '手机号码', '修改', "添加"], colModel: [ { name: 'int_rransportvehicle', index: 'int_rransportvehicle', hidden: true }, { name: 'vc_veh', index: 'vc_veh' }, { name: 'vc_phone', index: 'vc_veh' } , { name: 'edit', index: 'edit', width: 20, editable: false, formatter: idFormatEdit } , { name: 'add', index: 'add', width: 20, editable: false, formatter: idFormatAdd } ], rowNum: 10, rowList: [10, 20, 30], sortname: 'vc_veh', pager: "#pager", viewrecords: true, loadonce: true , onSelectRow: function (rowid) {
//事件的rowid和下面方法取的selectedid相同,现在表格控件的选中行的行id var selectedId = $("#list").jqGrid("getGridParam", "selrow");
//选中的行数据 var rowData = $("#list").jqGrid("getRowData", selectedId); } }).navGrid('#pager', { edit: false, add: false, del: false }); //格式化数据,三个参数必须依次 function idFormatEdit(cellvalue, options, rowObject) { return "<a href='./TransfortVehAdd.aspx?ID="+rowObject.int_rransportvehicle.toString()+ "&Edit=1'><img src='Styles/edit_16.png' style=\"cursor:pointer;\"/></a>"; }
function idFormatAdd(cellvalue, options, rowObject) { return "<a href='./TransfortVehAdd.aspx'><img src='Styles/add_16.png' style=\"cursor:pointer;\"/></a>"; }
利用ajax获取数据重新加载jgGrid表格显示数据
function getGridData(areaid, keywords) { $.post("Handler.ashx", { action: "getVehs", areaid: areaid, keywords: keywords }, function (ajax) { $("#list").jqGrid("clearGridData", true).trigger("reloadGrid"); $("#list").jqGrid('setGridParam', { datatype: "local", data: eval(ajax)//服务器返回的json格式,此处转换后给数据源赋值 }).trigger("reloadGrid"); }); }
服务端,需要引入Newtonsoft.Json.dll做json转换返回数据
public void ProcessRequest(HttpContext context) { context.Response.Buffer = true; context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1); context.Response.AddHeader("pragma", "no-cache"); context.Response.AddHeader("cache-control", ""); context.Response.CacheControl = "no-cache"; context.Response.ContentType = "text/plain"; string action = context.Request.Params["action"].ToString(); switch (action) { case "getVehs": getVehs(context); break; default: break; } } /// <summary> /// 获取交通车列表 /// </summary> /// <param name="context"></param> void getVehs(HttpContext context) { DataTable dt; string jsonData = string.Empty; DataSet sResult = DJ.DB.DataHelper.GetVehList(context.Request.Params["areaid"].ToString(), context.Request.Params["keywords"].ToString()); dt = sResult.Tables[0]; int iCount = dt.Rows.Count; IsoDateTimeConverter idtc = new IsoDateTimeConverter(); idtc.DateTimeFormat = "yyyy-MM-dd hh:mm:ss ffffff"; jsonData = JsonConvert.SerializeObject(dt, idtc).ToString(); context.Response.Write(jsonData); }
2、jqGrid以loadonce=false的方式获取数据,从服务器分页加载数据,每次分页器里面操作后会请求服务器数据,客户端分页参数自动附加到回传到服务端的请求参数里面
数据格式见下面jsonReader介绍
客户端
//请求服务器分页数据 jQuery("#list").jqGrid( { url: 'Handler.ashx?action=getVehs_test&areaid=' + $('[id$=hdAreaid]').val(), datatype: "json", jsonReader: { root: "griddata", total: "totalpages", page: "currpage", records: "totalrecords", repeatitems: false }, datatype: "json", height: 'auto', //width: '600', autowidth: true, colNames: ['车牌号码', '手机号码'], colModel: [ { name: 'vc_veh', index: 'vc_veh' }, { name: 'vc_phone', index: 'vc_veh' } ], rowNum: 20, rowList: [10, 20, 30], sortname: 'vc_veh', pager: "#pager", viewrecords: true, loadonce: true //caption: "车辆管理" }).navGrid('#pager', { edit: false, add: false, del: false });
服务端
#region 测试服务器分页返回数据 /// <summary> /// 测试服务器分页返回数据 /// </summary> /// <param name="context"></param> void getVehs_test(HttpContext context) { string jsonData = string.Empty; string sPage = HttpContext.Current.Request.Params["page"].ToString(); //当前请求第几页 int iPage = int.Parse(sPage); string sSize = HttpContext.Current.Request.Params["rows"].ToString(); //grid需要显示几行 int iSize = int.Parse(sSize); string sSidx = HttpContext.Current.Request.Params["sidx"].ToString(); //按什么排序 string sSord = HttpContext.Current.Request.Params["sord"].ToString(); //排序方式('desc'/'asc') var area = context.Request.Params["areaid"].ToString() ; var ds = DJ.DB.DataHelper.GetFenYeData(area, "bi_transportvehicles", "*", "where int_grouparea ="+area, "order by int_rransportvehicle", sPage, sSize, ""); IsoDateTimeConverter idtc = new IsoDateTimeConverter(); idtc.DateTimeFormat = "yyyy-MM-dd hh:mm:ss ffffff"; jsonData = JsonConvert.SerializeObject(ds.Tables[0], idtc).ToString(); string returnData = string.Empty; returnData = "{"; //总共多少页 returnData += "\"totalpages\""; returnData += ":"; returnData += "\""; returnData += Math.Ceiling(Convert.ToDecimal(ds.DataSetName) / Convert.ToInt32(sSize)); returnData += "\""; returnData += ","; //当前第几页 returnData += "\"currpage\""; returnData += ":"; returnData += "\""; returnData += sPage; returnData += "\""; returnData += ","; //总共多少记录 returnData += "\"totalrecords\""; returnData += ":"; returnData += "\""; returnData += ds.DataSetName; returnData += "\""; returnData += ","; //datable转换得到的JSON字符串 returnData += "\"griddata\""; returnData += ":"; returnData += jsonData; returnData += "}"; context.Response.Write(returnData); } #endregion
3、jsonReader介绍
jqGrid默认的jsonReader如下
jQuery("#gridid").jqGrid({ ... jsonReader : { root: "rows", page: "page", total: "total", records: "records", repeatitems: true, cell: "cell", id: "id", userdata: "userdata", subgrid: {root:"rows", repeatitems: true, cell:"cell" } }, ... });
服务端返回数据应对应如下
{ total: "xxx", page: "yyy", records: "zzz", rows : [ {id:"1", cell:["cell11", "cell12", "cell13"]},//cell11等是字段值 {id:"2", cell:["cell21", "cell22", "cell23"]}, ... ] }
/** * jqGrid默认期望返回的json对象格式要求如下: * {"page":"1","total":"2","records":"13", * "rows":[ * {id:"1",cell:["1","jancyxue","男","jancyxue@163.com","410958040","江西余干"]}, * {id:"2",cell:["2","linda","女","linda@163.com","111111111","湖南"]}, * {id:"3",cell:["3","jason","男","jason@sina.com","222222222","湖北"]}, * {id:"4",cell:["4","lucy","女","lucy@sina.com","33333333","北京"]} * ] * }
jsonReader参数:
root ,这个元素指明表格所需要的数据从哪里开始;
cell ,当前行所包含的单元格数据 ;
id ,行id ;
repeatitems,指明每行的数据是可以重复的,如果设为false,则会从返回的数据中按名字来搜索元素,这个名字就是colModel中的名字。
其他官网demo示例
jQuery("#gridid").jqGrid({ ... jsonReader : { root:"invdata", page: "currpage", total: "totalpages", records: "totalrecords" }, ... });
then the data should be { "totalpages": "xxx", "currpage": "yyy", "totalrecords": "zzz", "invdata" : [ {"id" :"1", "cell" :["cell11", "cell12", "cell13"]}, {"id" :"2", "cell" :["cell21", "cell22", "cell23"]}, ... ] }
jQuery("#gridid").jqGrid({ ... jsonReader : { root:"invdata", page: "currpage", total: "totalpages", records: "totalrecords", cell: "invrow" }, ... }); The data to match this description would be { "totalpages": "xxx", "currpage": "yyy", "totalrecords": "zzz", "invdata" : [ {"id" :"1", "invrow" :["cell11", "cell12", "cell13"]}, {"id" :"2", "invrow" :["cell21", "cell22", "cell23"]}, ... ] }
jQuery("#gridid").jqGrid({ ... jsonReader : { root:"invdata", page: "currpage", total: "totalpages", records: "totalrecords", cell: "invrow", id: "invid" }, ... }); The data for this description is: { "totalpages": "xxx", "currpage": "yyy", "totalrecords": "zzz", "invdata" : [ {"invid" :"1", "invrow" :["cell11", "cell12", "cell13"]}, {"invid" :"2", "invrow" :["cell21", "cell22", "cell23"]}, ... ] }
jQuery("#gridid").jqGrid({ ... jsonReader : { root:"invdata", page: "currpage", total: "totalpages", records: "totalrecords", cell: "", id: "0" }, ... }); In this case the id is the first element from the row data { "totalpages" : "xxx", "currpage" : "yyy", "totalrecords" : "zzz", "invdata" : [ ["1", "cell11", "cell12", "cell13"], ["2", "cell21", "cell22", "cell23"], ... ] }
jQuery("#gridid").jqGrid({ ... jsonReader : { root:"invdata", page: "currpage", total: "totalpages", records: "totalrecords", repeatitems: false, id: "0" }, ... }); The resulting data in our example should be: { "totalpages" : "xxx", "currpage" : "yyy", "totalrecords" : "zzz", "invdata" : [ {"invid" : "1","invdate":"cell11", "amount" :"cell12", "tax" :"cell13", "total" :"1234", "note" :"somenote"}, {"invid" : "2","invdate":"cell21", "amount" :"cell22", "tax" :"cell23", "total" :"2345", "note" :"some note"}, ... ] } The id element in this case is 'invid'. A very useful feature here (repeatitems:false) is that there is no need to include all the data that is represented in colModel.Since we make a search by name, the order does not need to match the order in colModel. Hence the following string will be correctly interpreted in jqGrid. { "totalpages" : "xxx", "currpage" : "yyy", "totalrecords" : "zzz", "invdata" : [ {"invid" :"1", "invdate" : "cell11", "note" :"somenote"}, {"invid" :"2", "amount" : "cell22", "tax" :"cell23", "total" :"2345"}, ... ] }
^_^ 天行健,君子以自强不息;地势坤,君子以厚德载物