根据实时数据在同一个DataGrid中显示不同字段,本身easyui并没有支持动态绑定列名,只有show属性显示或隐藏某字段。今天在网上看到直接修改easyui类库动态绑定列名的方法,废话不多说直接借用源码备份以后用。
先说一下思路:首先UI的datagrid中没有指定任何列,ajax提交成功后同时返回列的信息,先进行列的动态绑定,然后显示数据内容。
1.UI
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicDatagird.aspx.cs" 2 Inherits="WebUtils.DynamicDatagird" %> 3 4 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <title>动态datagrid</title> 8 <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> 9 <script src="Scripts/jquery.easyui.min.js" type="text/javascript"></script> 10 <link href="Style/themes/default/easyui.css" rel="stylesheet" type="text/css" /> 11 <script type="text/javascript"> 12 $(function () { 13 $('#tbUsers').datagrid({ 14 title: 'My Title', 15 width: 600, 16 height: 350, 17 dataType: 'json', 18 url: 'GetAjaxData.ashx?action=GetUserList2', 19 columns: [[]], 20 pagination: true, 21 pageSize: 5, //每页记录数 22 pageList: [5, 10, 15, 20, 30, 50], //分页记录数数组 23 onLoadSuccess: function (data, param) { 24 25 } 26 }); 27 }); 28 </script> 29 </head> 30 <body> 31 <form id="form1" runat="server"> 32 <div> 33 <table id="tbUsers"> 34 </table> 35 </div> 36 </form> 37 </body> 38 </html>
2.easyUI类库的修改(位置在datagrid ajax提交位置L6220处)
1 function _43f() { 2 $.ajax({ type: opts.method, url: opts.url, data: _43d, dataType: "json", success: function (data) { 3 //动态添加列 4 if (!!data && !!data.columns) { 5 var opts=$.data(_43a, "datagrid").options; 6 var _369 = $.data(_43a, "datagrid").panel; 7 var cols = $.data(_43a, "datagrid").options.columns[0]; 8 var colCount=cols.length; 9 if(colCount==0){ 10 //cols.slice(0,cols.length);//清除数组内容 11 for (var i = 0; i < data.columns.length; i++) { 12 var col = { 13 field: data.columns[i].field, 14 title: data.columns[i].title, 15 width: data.columns[i].width, 16 align: data.columns[i].align 17 }; 18 cols.push(col); 19 } 20 //UI添加列 21 if (colCount==0 && opts.columns) { 22 var t = _370(opts.columns); 23 $("div.datagrid-view2 div.datagrid-header-inner", _369).html(t); 24 } 25 } 26 } 27 setTimeout(function () { 28 _440(); 29 }, 0); 30 if(!!data && !!data.rows){ 31 _3a2(_43a, data); 32 } 33 setTimeout(function () { 34 _42d(_43a); 35 }, 0); 36 }, error: function () { 37 setTimeout(function () { 38 _440(); 39 }, 0); 40 if (opts.onLoadError) { 41 opts.onLoadError.apply(_43a, arguments); 42 } 43 } 44 }); 45 };
3.后台提供数据(一般处理程序)
public void GetUserList(HttpContext context) { String strJson = @"{ 'total':20, 'rows':[ {'name':'zhangsan01','age':'21','hobby':'001'}, {'name':'zhangsan02','age':'21','hobby':'001'}, {'name':'zhangsan03','age':'21','hobby':'001'}, {'name':'zhangsan04','age':'21','hobby':'001'}, {'name':'zhangsan05','age':'21','hobby':'001'} ], 'columns':[ {'field':'name','title':'Name','width':100,'align':'center'}, {'field':'age','title':'Age','width':100,'align':'center'}, {'field':'hobby','title':'Hobby','width':100,'align':'center'} ] }"; strJson = strJson.Replace("'", "/""); HttpResponse response = context.Response; response.ContentType = "text/json"; response.Write(strJson); }
这样就完成了动态绑定列名。功能是可以了,还不利于大量生产,需要提供自动集合转Json的类。
为此,我设计了一个JDataGrid类用于将List的集合生成我的DataGrid需要的数据格式(包含列的信息)。
1.定义User类,就作为实体类
namespace WebUtils { public class User { public string Name { get; set; } public int Age { get; set; } public string Gender { get; set; } public string Hobby { get; set; } } }
2.定义JDataGrid类和JColumn类
public class JDataGrid { public int total { get; set; } public List<Dictionary<string, object>> rows { get; set; } public List<JColumn> columns { get; set; } public static List<Dictionary<string, object>> ConvertRows(IList list) { List<Dictionary<string, object>> rowsList=new List<Dictionary<string, object>>(); if (list != null) { foreach (object obj in list) { Dictionary<string, object> dic = new Dictionary<string, object>(); Type t = obj.GetType(); foreach (PropertyInfo pi in t.GetProperties()) { string key = pi.Name; object value=pi.GetValue(obj, null); dic.Add(key, value); } rowsList.Add(dic); } } return rowsList; } public string ConvertToJson() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("{{/"total/":{0},/"rows/":[", total); //添加数据 if (rows != null && rows.Count > 0) { for (int i = 0; i < rows.Count; i++) { sb.Append("{"); foreach (string key in rows[i].Keys) { if (rows[i][key] is ValueType) { sb.AppendFormat("/"{0}/":{1},", key, rows[i][key]); } else { sb.AppendFormat("/"{0}/":/"{1}/",", key, rows[i][key]); } } sb.Remove(sb.Length - 1, 1); sb.Append("}"); if (i != rows.Count - 1) { sb.Append(","); } } } sb.Append("],"); sb.Append("/"columns/":["); //添加列 if (columns != null && columns.Count > 0) { for (int i = 0; i < columns.Count; i++) { sb.Append(columns[i].ConvertToJson()); if (i != columns.Count - 1) { sb.Append(","); } } } sb.Append("]}"); string str=sb.ToString(); return str; } } public class JColumn { public int rowspan { get; set; } public int colspan { get; set; } public bool checkbox { get; set; } public string field { get; set; } public string title { get; set; } public int width { get; set; } public string align { get; set; } public string ConvertToJson() { StringBuilder sb = new StringBuilder(); sb.Append("{"); if (rowspan != null) { sb.AppendFormat("/"rowspan/":{0},", rowspan); } if (colspan != null) { sb.AppendFormat("/"colspan/":{0},", colspan); } if (checkbox != null) { sb.AppendFormat("/"checkbox/":{0},", checkbox); } sb.AppendFormat("/"field/":/"{0}/",", field); sb.AppendFormat("/"width/":{0},", width); sb.AppendFormat("/"align/":/"{0}/",", align); sb.AppendFormat("/"title/":/"{0}/",", title); sb.Remove(sb.Length - 1, 1); sb.Append("}"); String str = sb.ToString(); return str; } }
3.后台获取数据(一般处理程序)
public void GetUserList2(HttpContext context) { List<User> userList = new List<User>(); for (int i = 0; i < 10; i++) { userList.Add(new User { Name = "Name" + (i + 1), Age = 20 + i, Gender = i % 3 == 0 ? "男" : "女", Hobby = i.ToString() }); } List<JColumn> colList = new List<JColumn>() { new JColumn{field="Name",title="姓名",width=100,align="center"}, new JColumn{field="Age",title="年龄",width=100,align="center"}, new JColumn{field="Gender",title="性别",width=50,align="center"}, new JColumn{field="Hobby",title="兴趣",width=150,align="center"}, }; JDataGrid dg = new JDataGrid { total=20, rows=JDataGrid.ConvertRows(userList), columns=colList, }; string strJson = dg.ConvertToJson(); HttpResponse response = context.Response; response.ContentType = "text/json"; response.Write(strJson); }
对比前面的方法,显示代码通用多了