項目中使用jqgrid展現數據,最近遇到這樣一個問題,須要根據數據庫中的關聯關係動態生成列,解決方案以下:ajax
前臺代碼:數據庫
$(document).ready(function () { var ColN, ColM, ColD, capEN; var sPath = window.location.pathname; var sPage = sPath.substring(sPath.lastIndexOf('/') + 1); //alert(sPage); $.ajax({ url: sPage+'?method=getGridHeadData', type: "POST", contentType: "application/json; charset=utf-8", data: {}, dataType: "json", success: function (data, st) { if (st == "success") { ColN = data.rowsHead;//jqgrid heading data ColM = data.rowsM; // its column model ColD = data.rows; // Data createGrid(); } }, error: function () { alert("Error with AJAX callback"); } }); function createGrid() { jQuery("#AccountingCodesGrid").jqGrid({ datatype: 'json', url: sPage+'?method=getGridData', mtype: 'POST', ajaxGridOptions: { contentType: 'application/json; charset=utf-8' }, serializeGridData: function (postData) { return JSON.stringify(postData); }, jsonReader: { repeatitems: false, root: "rows", page: "page", total: "total", records: "records" }, //data: ColD, colNames: ColN, colModel: ColM, loadonce: true, pager: jQuery('#pager'), rowNum: 5, rowList: [5, 10, 20, 50], viewrecords: true }) } jQuery("#AccountingCodesGrid").jqGrid('navGrid', '#Pager', { edit: false, add: false, del: false }, null, null, true, { multipleSearch: true }); var height = $(window).height(); });
後臺代碼:json
if (Request.QueryString["method"] == "getGridData") { Request.InputStream.Position = 0; StreamReader ipStRdr = new StreamReader(Request.InputStream); string json = ipStRdr.ReadToEnd(); JavaScriptSerializer jser = new JavaScriptSerializer(); Dictionary<string,> dict = jser.Deserialize<dictionary><string,>>(json); getGridData(int.Parse(dict["page"].ToString()), int.Parse(dict["rows"].ToString()), bool.Parse(dict["_search"].ToString()), dict["sord"].ToString()); Response.End(); } else if (Request.QueryString["method"] == "getGridHeadData") { getGridHeadData(); Response.End(); }
獲取數據的方法:app
public void getGridData(int page, int rows, bool _search, string sord) { DataTable dtRecords = dtSource;// Data Table int recordsCount = dtRecords.Rows.Count; JqGridData objJqGrid = new JqGridData(); objJqGrid.page = page; objJqGrid.total = ((recordsCount + rows - 1) / rows); objJqGrid.records = recordsCount; objJqGrid.rows = ConvertDT(dtRecords); List<string> liob = new List<string>(); foreach (DataColumn column in dtRecords.Columns) { liob.Add(column.ColumnName); } objJqGrid.rowsHead = liob; List<object> colcontetn = new List<object>(); foreach (var item in liob) { JqGridDataHeading obj = new JqGridDataHeading(); obj.name = item.ToString(); obj.index = item.ToString(); colcontetn.Add(obj); } objJqGrid.rowsM = colcontetn; JavaScriptSerializer jser = new JavaScriptSerializer(); Response.Write(jser.Serialize(objJqGrid)); }