EasyUI 1.3.1 datagrid动态绑定列名和数据

来源:互联网 发布:js实现div旋转 编辑:程序博客网 时间:2024/04/28 05:14

很多网友对【easyui datagrid动态绑定列名和数据 】存在很多疑惑,实验后不能成功,这是因为不同版本的EasyUI源码不同。我就最新的版本的EasyUI 1.3.1做了示例,并简化了后台代码实现。

简单介绍一下,动态绑定列名的业务场景:当系统存在角色、权限信息时,可能需要对表格进行字段权限分配,举例说:A角色能查看员工表A、B、C、D字段,B角色能查看员工A、B、D、F、G字段,C角色能查看员工A、D、E字段,这样对于表格而言字段是动态的,不能在写页面时静态写死,必须通过后台系统获取。那么我们需要对EasyUI datagrid进行改造。

改造方案:
1.静态页面使用空的列信息

$('#tbEmployee').datagrid({ title: '……', pagination: true, url: '……', columns: [[]]});

2.传输的数据改造
EasyUI datagrid获取的数据格式

{                                                       "total":239,                                                       "rows":[{……},{……},{……},{……},{……}]                                                          } 

改造后在json中加入动态的列信息

{                                                       "total":239,                                                       "rows":[{……},{……},{……},{……},{……}], "cols":[{……},{……}]} 

3.改造动态加载列,这是最难实现的步骤
原本想在onLoadSuccess中加载列,结果未实现,想来想去是因为默认构造的列是通过框架生成html代码的。
改变方案,应该在$.ajax请求完数据后动态加载,找到

function _53b(){var _53c=opts.loader.call(_538,_53a,function(data){setTimeout(function(){$(_538).datagrid("loaded");},0);_4b1(_538,data);setTimeout(function(){_52b(_538);},0);}

opts.loader.call会调用ajax异步请求,所以应该在请求后得到数据时构造列

function _53b(){var _53c=opts.loader.call(_538,_53a,function(data){//add dynamic columnsif(data!=null && data.cols!=null){    var opts=$.data(_538, "datagrid").options;               var cols = $.data(_538, "datagrid").options.columns[0];          var colCount=cols.length;    if(colCount==0){                 for (var i = 0; i < data.cols.length; i++) {                 var col = {                     field: data.cols[i].field,                     title: data.cols[i].title,                     width: data.cols[i].width              };                 cols.push(col);             }             //UI添加列             if (colCount==0 && opts.columns) {                 _461(_538);       }          }    }setTimeout(function(){$(_538).datagrid("loaded");},0);_4b1(_538,data);setTimeout(function(){_52b(_538);},0);}

注意:_461(_538);是动态添加列的html方法,比较难找到。

完整代码:
WEB页面:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicDataTable.aspx.cs" Inherits="MyWeb.DynamicDataTable" %><!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></title>    <link href="js/easyui/themes/default/easyui.css" rel="stylesheet" type="text/css" />    <link href="js/easyui/themes/icon.css" rel="stylesheet" type="text/css" />    <script src="js/jquery-1.8.0.min.js" type="text/javascript"></script>    <script src="js/easyui/jquery.easyui.min.js" type="text/javascript"></script>    <script src="js/jquery.json/jquery.json-2.2.min.js" type="text/javascript"></script>    <script type="text/javascript">        $(function () {            $('#tbEmployee').datagrid({                title: 'Customer Infos',                width: 700,                height: 350,                nowrap: true,                pagination: true,                rownumbers: true,                url: 'Services/EmployeeService.asmx/GetCustomerList',                columns: [[]]            });        });    </script></head><body>    <form id="form1" runat="server">    <div>        <table id="tbEmployee">        </table>    </div>    </form></body></html>

WebService代码:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services;using Newtonsoft.Json;using Newtonsoft.Json.Linq;using System.Web.Script.Services;namespace MyWeb.Services {    /// <summary>    /// EmployeeService 的摘要说明    /// </summary>    [WebService(Namespace = "http://tempuri.org/")]    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]    [System.ComponentModel.ToolboxItem(false)]    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。    [System.Web.Script.Services.ScriptService]    public class EmployeeService : System.Web.Services.WebService {        [WebMethod]        public void GetCustomerList() {            //获取当前用户信息            //获取当前可用的列            //获取可见的数据            NorthwindEntities db=new NorthwindEntities();            //可见记录的总数            int count = db.Customers.Count();            //分页信息            int page = Convert.ToInt32(Context.Request.Form["page"]);            int rows = Convert.ToInt32(Context.Request.Form["rows"]);            //可见记录            List<Customers> cusList = db.Customers.OrderBy(c => c.CustomerID).Skip((page - 1) * rows).Take(rows).ToList();            //拼凑成JSON对象            JObject result = new JObject(                new JProperty("total", count),                new JProperty("rows", new JArray(                    from c in cusList                    select new JObject(                        new JProperty("CustomerID", c.CustomerID),                        new JProperty("Name", c.ContactName),                        new JProperty("City",c.City),                        new JProperty("Address",c.Address)                    )                ))            );            //模拟数据(应该为从数据库获取可见列的配置信息)            List<EColumn> colList = new List<EColumn>() {                new EColumn{Field="CustomerID",Title="编号",Width=80},                new EColumn{Field="Name",Title="姓名",Width=80},                new EColumn{Field="City",Title="城市",Width=80},                new EColumn{Field="Address",Title="地址",Width=120},            };            JArray cols = new JArray(                from c in colList                select new JObject(                    new JProperty("field", c.Field),                    new JProperty("title", c.Title),                    new JProperty("width", c.Width),                    new JProperty("sortable", c.Sortable),                    new JProperty("checkbox", c.Checkbox)                )            );            result.Add(new JProperty("cols", cols));            Context.Response.ContentType = "application/json;utf-8";            Context.Response.Write(result.ToString());        }    }}


 

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace MyWeb {    [Serializable]    public class EColumn {        public string Field { get; set; }        public double Width { get; set; }        public string Title { get; set; }        public bool Sortable { get; set; }        public bool Checkbox { get; set; }    }}


Web.config

<?xml version="1.0" encoding="utf-8"?><!--  有关如何配置 ASP.NET 应用程序的详细消息,请访问  http://go.microsoft.com/fwlink/?LinkId=169433  --><configuration>  <system.web>    <compilation debug="true" targetFramework="4.0">      <assemblies>        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />      </assemblies>    </compilation>  </system.web>  <connectionStrings>    <add name="NorthwindEntities" connectionString="metadata=res://*/Northwind.csdl|res://*/Northwind.ssdl|res://*/Northwind.msl;provider=System.Data.SqlClient;provider connection string="data source=vxp;initial catalog=Northwind;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  </connectionStrings></configuration>


使用时需要注意:1.修改数据库连接字符串;2.添加Northwind示例数据库(网上有下载)
源码示例见:EasyUI 1.3.1动态表格列示例

原创粉丝点击