easyui datagrid动态绑定列名和数据

公司有这么一个需求,根据不同的权限显示一张表不同的字段。这个要命的需求给UI层带来不少麻烦,首先,我们采用easyUI的datagrid显示表格数据,而表格的列是静态写死的,如果要根据不同权限显示不同的字段导致必须通过结果集来show字段,但是easyUI的源代码中是ajax拿到数据后直接根据列去显示,使得我不得不修改easyUI类库。

先说一下思路:首先UI的datagrid中没有指定任何列,ajax提交成功后同时返回列的信息,先进行列的动态绑定,然后显示数据内容。

1.UI

Code:
  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处)

Code:
  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.后台提供数据(一般处理程序)

Code:
  1.        public void GetUserList(HttpContext context) {      
  2.             string strJson = @"{      
  3. 'total':20,      
  4. 'rows':[      
  5. {'name':'zhangsan01','age':'21','hobby':'001'},      
  6. {'name':'zhangsan02','age':'21','hobby':'001'},      
  7. {'name':'zhangsan03','age':'21','hobby':'001'},      
  8. {'name':'zhangsan04','age':'21','hobby':'001'},      
  9. {'name':'zhangsan05','age':'21','hobby':'001'}      
  10. ],      
  11. 'columns':[      
  12. {'field':'name','title':'Name','width':100,'align':'center'},      
  13. {'field':'age','title':'Age','width':100,'align':'center'},      
  14. {'field':'hobby','title':'Hobby','width':100,'align':'center'}      
  15. ]      
  16. }";      
  17.             strJson = strJson.Replace("'""/"");      
  18.             HttpResponse response = context.Response;      
  19.             response.ContentType = "text/json";      
  20.             response.Write(strJson);      
  21.         }    

这样就完成了动态绑定列名。功能是可以了,还不利于大量生产,需要提供自动集合转Json的类。
为此,我设计了一个JDataGrid类用于将List的集合生成我的DataGrid需要的数据格式(包含列的信息)。

1.定义User类,就作为实体类

Code:
  1. namespace WebUtils {      
  2.     public class User {      
  3.         public string Name { getset; }      
  4.         public int Age { getset; }      
  5.         public string Gender { getset; }      
  6.         public string Hobby { getset; }      
  7.     }      
  8. }    

2.定义JDataGrid类和JColumn类

Code:
  1. public class JDataGrid {      
  2.      
  3.     public int total { getset; }      
  4.     public List<Dictionary<stringobject>> rows { getset; }      
  5.     public List<JColumn> columns { getset; }      
  6.      
  7.     public static List<Dictionary<stringobject>> ConvertRows(IList list) {      
  8.         List<Dictionary<stringobject>> rowsList=new List<Dictionary<stringobject>>();      
  9.         if (list != null) {      
  10.             foreach (object obj in list) {      
  11.                 Dictionary<stringobject> dic = new Dictionary<stringobject>();      
  12.                 Type t = obj.GetType();      
  13.                 foreach (PropertyInfo pi in t.GetProperties()) {      
  14.                     string key = pi.Name;      
  15.                     object value=pi.GetValue(obj, null);      
  16.                     dic.Add(key, value);      
  17.                 }      
  18.                 rowsList.Add(dic);      
  19.             }      
  20.         }      
  21.         return rowsList;      
  22.     }      
  23.      
  24.     public string ConvertToJson() {      
  25.         StringBuilder sb = new StringBuilder();      
  26.         sb.AppendFormat("{{/"total/":{0},/"rows/":[", total);      
  27.         //添加数据      
  28.         if (rows != null && rows.Count > 0) {      
  29.             for (int i = 0; i < rows.Count; i++) {      
  30.                 sb.Append("{");      
  31.                 foreach (string key in rows[i].Keys) {      
  32.                     if (rows[i][key] is ValueType) {      
  33.                         sb.AppendFormat("/"{0}/":{1},", key, rows[i][key]);      
  34.                     } else {      
  35.                         sb.AppendFormat("/"{0}/":/"{1}/",", key, rows[i][key]);      
  36.                     }      
  37.                 }      
  38.                 sb.Remove(sb.Length - 1, 1);      
  39.                 sb.Append("}");      
  40.                 if (i != rows.Count - 1) {      
  41.                     sb.Append(",");      
  42.                 }      
  43.             }      
  44.         }      
  45.         sb.Append("],");      
  46.         sb.Append("/"columns/":[");      
  47.         //添加列      
  48.         if (columns != null && columns.Count > 0) {      
  49.             for (int i = 0; i < columns.Count; i++) {      
  50.                 sb.Append(columns[i].ConvertToJson());      
  51.                 if (i != columns.Count - 1) {      
  52.                     sb.Append(",");      
  53.                 }      
  54.             }      
  55.         }      
  56.         sb.Append("]}");      
  57.         string str=sb.ToString();      
  58.         return str;      
  59.     }      
  60. }      
  61.      
  62. public class JColumn {      
  63.     public int? rowspan { getset; }      
  64.     public int? colspan { getset; }      
  65.     public bool? checkbox { getset; }      
  66.     public string field { getset; }      
  67.     public string title { getset; }      
  68.     public int width { getset; }      
  69.     public string align { getset; }      
  70.      
  71.     public string ConvertToJson() {      
  72.         StringBuilder sb = new StringBuilder();      
  73.         sb.Append("{");      
  74.         if (rowspan != null) {      
  75.             sb.AppendFormat("/"rowspan/":{0},", rowspan);      
  76.         }      
  77.         if (colspan != null) {      
  78.             sb.AppendFormat("/"colspan/":{0},", colspan);      
  79.         }      
  80.         if (checkbox != null) {      
  81.             sb.AppendFormat("/"checkbox/":{0},", checkbox);      
  82.         }      
  83.         sb.AppendFormat("/"field/":/"{0}/",", field);      
  84.         sb.AppendFormat("/"width/":{0},", width);      
  85.         sb.AppendFormat("/"align/":/"{0}/",", align);      
  86.         sb.AppendFormat("/"title/":/"{0}/",", title);      
  87.         sb.Remove(sb.Length - 1, 1);      
  88.         sb.Append("}");      
  89.         string str = sb.ToString();      
  90.         return str;      
  91.     }      
  92. }     

3.后台获取数据(一般处理程序)

Code:
  1. public void GetUserList2(HttpContext context) {      
  2.      List<User> userList = new List<User>();      
  3.      for (int i = 0; i < 10; i++) {      
  4.          userList.Add(new User {      
  5.              Name = "Name" + (i + 1),      
  6.              Age = 20 + i,      
  7.              Gender = i % 3 == 0 ? "男" : "女",      
  8.              Hobby = i.ToString()      
  9.          });      
  10.      }      
  11.      List<JColumn> colList = new List<JColumn>() {      
  12.          new JColumn{field="Name",title="姓名",width=100,align="center"},      
  13.          new JColumn{field="Age",title="年龄",width=100,align="center"},      
  14.          new JColumn{field="Gender",title="性别",width=50,align="center"},      
  15.          new JColumn{field="Hobby",title="兴趣",width=150,align="center"},      
  16.      };      
  17.      JDataGrid dg = new JDataGrid {      
  18.          total=20,      
  19.          rows=JDataGrid.ConvertRows(userList),      
  20.          columns=colList,      
  21.      };      
  22.      string strJson = dg.ConvertToJson();      
  23.      HttpResponse response = context.Response;      
  24.      response.ContentType = "text/json";      
  25.      response.Write(strJson);      
  26.  }    

对比前面的方法,显示代码通用多了。

演示下载

  • 0
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值