后台组装colNames以及colModel:
楼主这里是两个固定列+(开始日期—结束日期)之间的时间列
ps:begin为开始日期,End为结束日期
public class DataGridSale
{
public string HeaderName { get; set; }//列标题
public string BindingValue { get; set; }//数据对应列
}
List<DataGridSale> dataGridSaleList = new List<DataGridSale>();
dataGridSaleList.Add(new DataGridSale{HeaderName = "名称",BindingValue = "ShopName"});
dataGridSaleList.Add(new DataGridSale{HeaderName = "总计",BindingValue = "RealSumCurr"});
for (DateTime i = begin; i <= End; i = i.AddDays(1))
{
var j = i.Day;
DataGridSale grid = new DataGridSale(){
HeaderName = i.ToString("M-d"),//label
BindingValue = "DAY" + i.ToString("MMdd")//name
};
dataGridSaleList.Add(grid);
}
string[] colNames = new string[dataGridSaleList.Count+1];
Object[] colModel = new Object[dataGridSaleList.Count+1];
//因为前端需要用到ID,所以添加在最后,并隐藏,不需要的可以删除+1,以及下面两句赋值代码
colNames[dataGridSaleList.Count] = "ID";//设置最后一列为ID
colModel[dataGridSaleList.Count] = new { name = "ID", hidden = true, key = true, width = 100, sortable = false };//设置最后一列为主键
//组装colNames和colModel
int c = 0;
foreach (var GridSale in dataGridSaleList)
{
colNames[c] = GridSale.HeaderName;
var colm = new{name = GridSale.BindingValue,width = 100,align = "left",frozen=false,//设置不冻结列 sortable = false//设置不排序};
if (c < 2)
colm = new{name = GridSale.BindingValue,width = 100,align = "left",frozen=true,//设置冻结前两列 sortable=false//设置列不排序};
colModel[c] = colm;
c++;
}
//组装数据
var data = GetShopDaySaleByDate(begin,End); //获取数据 ps:数据格式Dictionary<key, value>
//然后新建一个实体(DayEntity)装载上面组装的数据
DayEntity de = new DayEntity();
de.colNs = colNames;
de.colMS = colModel;
de.colModelList = data;
//////////////////////////////至此后台已组装完成,传递至前端解析
获取后台传递的数据
$(function () {
GetDynamicCols(1);
})
index:判断是加载界面还是清除界面,因为每次重新加载界面必须先清除界面,1.加载,2清除
function GetDynamicCols(index) {
$.ajax({
type: "Get",
async: false,
url: "请求数据的地址“,
success: function (datajson) {
if (index == 1) {
var data = jQuery.parseJSON(datajson);
//数据页
var colModelList = eval(data.colModelList)
var colNs = eval(data.colNs);
var colMS = eval(data.colMS);
gridList(colNs, colMS, colModelList);
} else {
jQuery("#gridList").gridUnload("gridList");
jQuery("#gridList").jqGrid('clearGridData');
GetDynamicCols(1);
}
}
});
}
//显示界面
function gridList(colNs, colMS, colModelList) {
var $gridList = $("#gridList");
$gridList.dataGrid({
height: $(window).height() - $(window).height() / 1.5,
colNames: colNs,//列名称
colModel: colMS,//列属性
viewrecords: true,//显示记录数
rowNum: -1,设置返回记录count为可显示行数
beforeSelectRow: function (ID) {//行点击事件(点击之前,onSelectRow点击之时)
var shopid = $("#gridList").jqGrid("getRowData", ID).shopid;
GetShopTurnoverChart(shopid);
},
});
jQuery("#gridList").jqGrid('setFrozenColumns');//冻结列
for (var i = 0; i <= colModelList.length; i++) {
jQuery("#gridList").jqGrid('addRowData', i + 1, colModelList[i]);//加载数据
}
$("#btn_search").click(function () {
GetDynamicCols(2);//查询按钮,查询的时候先清除界面
});
}
好了,至此动态加载jqGrid完成