公司有这么一个需求,根据不同的权限显示一张表不同的字段。这个要命的需求给UI层带来不少麻烦,首先,我们采用easyUI的datagrid显示表格数据,而表格的列是静态写死的,如果要根据不同权限显示不同的字段导致必须通过结果集来show字段,但是easyUI的源代码中是ajax拿到数据后直接根据列去显示,使得我不得不修改easyUI类库。
先说一下思路:首先UI的datagrid中没有指定任何列,ajax提交成功后同时返回列的信息,先进行列的动态绑定,然后显示数据内容。
1.UI
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicDatagird.aspx.cs"
- Inherits="WebUtils.DynamicDatagird" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>动态datagrid</title>
- <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
- <script src="Scripts/jquery.easyui.min.js" type="text/javascript"></script>
- <link href="Style/themes/default/easyui.css" rel="stylesheet" type="text/css" />
- <script type="text/javascript">
- $(function () {
- $('#tbUsers').datagrid({
- title: 'My Title',
- width: 600,
- height: 350,
- dataType: 'json',
- url: 'GetAjaxData.ashx?action=GetUserList2',
- columns: [[]],
- pagination: true,
- pageSize: 5, //每页记录数
- pageList: [5, 10, 15, 20, 30, 50], //分页记录数数组
- onLoadSuccess: function (data, param) {
- }
- });
- });
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <table id="tbUsers">
- </table>
- </div>
- </form>
- </body>
- </html>
2.easyUI类库的修改(位置在datagrid ajax提交位置L6220处)
- function _43f() {
- $.ajax({ type: opts.method, url: opts.url, data: _43d, dataType: "json", success: function (data) {
- //动态添加列
- if (!!data && !!data.columns) {
- var opts=$.data(_43a, "datagrid").options;
- var _369 = $.data(_43a, "datagrid").panel;
- var cols = $.data(_43a, "datagrid").options.columns[0];
- var colCount=cols.length;
- if(colCount==0){
- //cols.slice(0,cols.length);//清除数组内容
- for (var i = 0; i < data.columns.length; i++) {
- var col = {
- field: data.columns[i].field,
- title: data.columns[i].title,
- width: data.columns[i].width,
- align: data.columns[i].align
- };
- cols.push(col);
- }
- //UI添加列
- if (colCount==0 && opts.columns) {
- var t = _370(opts.columns);
- $("div.datagrid-view2 div.datagrid-header-inner", _369).html(t);
- }
- }
- }
- setTimeout(function () {
- _440();
- }, 0);
- if(!!data && !!data.rows){
- _3a2(_43a, data);
- }
- setTimeout(function () {
- _42d(_43a);
- }, 0);
- }, error: function () {
- setTimeout(function () {
- _440();
- }, 0);
- if (opts.onLoadError) {
- opts.onLoadError.apply(_43a, arguments);
- }
- }
- });
- };
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);
- }
对比前面的方法,显示代码通用多了。
演示下载