根據實時數據在同一個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); }
對比前面的方法,顯示代碼通用多了