一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

详解jquery插件treegrid树状表格的使用方法(.Net平台)

时间:2022-06-25 17:23:44 编辑:袖梨 来源:一聚教程网

上一篇介绍了DataTable,这一篇在DT的基础之上再使用jquery的一款插件:treegrid,官网地址:http://maxazan.github.io/jquery-treegrid/

一、使用treegrid,需要以下支持

jquery.min.js+jquery.treegrid.min.js

二、后端提供树状列表格式的集合数据,借助前端的DT的配置控制,来在页面上输出满足treegrid格式要求的html

前台:

 
          
            
            
            
            
            
            
          
        
      
 代码如下 复制代码
@using Model
@{
  Layout = null;
  UserInfo userInfo = null;
 
  if (ViewData["LoginUser"] != null)
  {
    userInfo = ViewData["LoginUser"] as UserInfo;
  }
  else
  {
    Response.Redirect("/Login/Index");
  }
}
  
  
  
  用户列表
  
  
  
  
  
  
  
  
    
      @Html.Partial("CRUDBtn", userInfo)
    
 
    
      
        
checkbox"name=""value=""> 菜单名 请求路径 描述 添加时间 修改时间
    
  
  
javascript">
  var table1 = null;
  $(function () {
    table1 = initializeTable();
    clickDeal();
  });
  /*点击处理*/
  function clickDeal() {
    var addBtn = $("#add");
    var deleteBtn = $("#delete");
    var editBtn = $("#edit");
    var viewBtn = $("#view");
    $("#search").click(function () {
      table1.ajax.reload();
      return false;
    });
    if (addBtn != null) {
      addBtn.click(function () {
        var title = $(this).text().substring(1).trim();
        var url = $(this).attr("url");
 
        layer_show(title, url, 600, 360);
      });
    }
    if (deleteBtn != null) {
      deleteBtn.click(function () {
        var idArr = [];
        var url = $(this).attr("url");
        $("input:checkbox[name=id]:checked").each(function () {
          var item = this;
          idArr.push($(item).val());
        });
        if (idArr.length == 0) {
          layer.msg("请至少选择一个选项", { icon: 2, time: 2000 });
        }
        else {
          layer.confirm('确认要删除吗?', function (index) {
            var loadIndex = layer.load();
            $.ajax({
              url: url,
              type: "post",
              data: { "idArrStr": idArr.toString() },
              dataType: "json",
              success: function (data) {
                if (data.Pass) {
                  layer.close(loadIndex);
                  layer.msg(data.Msg, { icon: 1, time: 2000 });
 table1.ajax.reload(null, false);
                } else {
                  layer.msg(data.Msg, { icon: 1, time: 2000 });
                }
              },
              error: function (msg) {
                layer.msg(msg.status);
              }
            });
          });
        }
      });
    }
    if (editBtn != null) {
      editBtn.click(function () {
        var idArr = [];
        var title = $(this).text().substring(1).trim();
        var url = $(this).attr("url");
        $("input:checkbox[name=id]:checked").each(function () {
          var item = this;
          idArr.push($(item).val());
        });
        if (idArr.length != 1) {
          layer.msg("请选择一个选项", { icon: 2, time: 2000 });
        }
        else {
          url += "?id=" + idArr[0];
          layer_show(title, url, 600, 360);
        }
      });
    }
    if (viewBtn != null) {
      viewBtn.click(function () {
        var idArr = [];
        var title = $(this).text().substring(1).trim();
        var url = $(this).attr("url");
        $("input:checkbox[name=id]:checked").each(function () {
          var item = this;
          idArr.push($(item).val());
        });
        if (idArr.length != 1) {
          layer.msg("请选择一个选项", { icon: 2, time: 2000 });
        }
        else {
          url += "?id=" + idArr[0];
          layer_show(title, url, 600, 360);
        }
      });
    }
  }
  /*初始化table*/
  function initializeTable() {
    var table = $("#table1").DataTable({
      /****************************************表格数据加载****************************************************/
      "serverSide": true,
      "ajax": {//ajax请求数据源
        "url": "/Power/Manager/Search",
        "type": "post",
        "data": function (data) {//添加额外的数据给服务器
        }
      },
      "columns": [//列绑定
        { "defaultContent": "" },
        { "data": "PowerName" },
        { "data": "Url" },
        { "data": "Description" },
        { "data": "AddTime" },
        { "data": "ModifyTime" }
      ],
      "columnDefs": [//列定义
        {
          "targets": [0],
          "data": "PowerId",
          "render": function (data, type, full) {//全部列值可以通过full.列名获取,一般单个列值用data PS:这里的render是有多少列就执行多少次方法。。。不知道为啥
            return "";
          }
        },
        {
          "targets": [4],
          "data": "AddTime",
          "render": function (data, type, full) {//全部列值可以通过full.列名获取,一般单个列值用data PS:这里的render是有多少列就执行多少次方法。。。不知道为啥
            if (data == null || data.trim() == "") { return "/"; }
            else {
              var dateTime = new Date(parseInt(data.replace("/Date(", "").replace(")/", ""), 10));
              var month = dateTime.getMonth() + 1 <10? "0" + (dateTime.getMonth() + 1) : dateTime.getMonth() + 1;
              vardate=dateTime.getDate() < 10 ? "0" + dateTime.getDate() : dateTime.getDate();
              return dateTime.getFullYear() + "/" + month + "/" + date;
            }
          }
        },
        {
          "targets": [5],
          "data": "ModifyTime",
          "render": function (data, type, full) {//全部列值可以通过full.列名获取,一般单个列值用data PS:这里的render是有多少列就执行多少次方法。。。不知道为啥
            if (data == null || data.trim() == "") { return "/"; }
            else {
              vardateTime=newDate(parseInt(data.replace("/Date(", "").replace(")/", ""), 10));
              varmonth=dateTime.getMonth() + 1 < 10 ? "0" + (dateTime.getMonth() + 1) : dateTime.getMonth() + 1;
              vardate=dateTime.getDate() < 10 ? "0" + dateTime.getDate() : dateTime.getDate();
              return dateTime.getFullYear() + "/" + month + "/" + date;
            }
          }
        },
      ],
      "rowCallback": function (row, data, displayIndex) {//行定义
        if (data.ParentId != "0") {
          $(row).attr("class", "text-c treegrid-" + data.PowerId + " treegrid-parent-" + data.ParentId);
        } else {
          $(row).attr("class", "text-c treegrid-" + data.PowerId);
        }
      },
      "initComplete": function (settings, json) { //表格初始化完成后调用
        $("#table1").treegrid({
          "initialState": 'collapsed',
        });
      },
      /****************************************表格数据加载****************************************************/
      /****************************************表格样式控制****************************************************/
      "dom": "t<'dataTables_info'il>p",//表格布局
      "processing": true,//等待加载效果
      "language": {//语言国际化
        "lengthMenu": "每页 _MENU_ 条",
        "zeroRecords": "没有找到记录",
        "info": "当前显示 _START_ 到 _END_ 条,共 _TOTAL_条",
        "infoEmpty": "无记录",
        "paginate":
        {
          "first": "首页",
          "previous": "前一页",
          "next": "后一页",
          "last": "末页"
        },
        "processing": "表格在努力渲染中......",
        "loadingRecords": "加载记录中...",//注意该参数在从服务器加载的时候无效,只有Ajax和客户端处理的时候有效
      },
      "paging": false,//分页功能
      "ordering": false,//排序功能
      "autoWidth": false,//自动宽度(这里关闭后,可以随着左侧的隐藏而扩展页面一起100%宽度)
      /****************************************表格样式控制****************************************************/
    });
    return table;
  }
 

后台:

 
 代码如下 复制代码
publicActionResult Search(DataTable dt)
  {
   inttotal;
   IQueryable powerIq = CurrentBllSession.PowerBll.GetIQueryable();
   total = powerIq.Count();
   List powerList = powerIq.ToList();
   powerList = TreeGridList(powerList);
   dt.recordsTotal = total;
   dt.recordsFiltered = total;
   dt.data = powerList;
   returnJson(dt);
  }
  ///
  /// 将List转换为TreeGrid格式的List
  ///
  privateList TreeGridList(List powerList)
  {
   List treegridList=newList();
   foreach(var powerOneinpowerList.Where(a => a.ParentId =="0"|| a.PowerId.Length == 4).OrderBy(a => a.Sort))//一级菜单
   {
    treegridList.Add(powerOne);
    foreach(var powerTwoinpowerList.Where(a => a.ParentId !="0"&& a.PowerId.Length == 8 && a.ParentId == powerOne.PowerId).OrderBy(a=>a.Sort))//二级菜单
    {
     treegridList.Add(powerTwo);
     foreach(var powerBtninpowerList.Where(a => a.ParentId !="0"&& a.PowerId.Length == 8 && a.ParentId == powerTwo.PowerId).OrderBy(a => a.Sort))//按钮
     {
      treegridList.Add(powerBtn);
     }
    }
   }
   returntreegridList;
  }
 

解释说明:

treegrid是通过tr标签上的class内容和tr的位置关系来组织表格中行之间的父子关系和位置关系的,

DT中的配置项:

 "rowCallback": function (row, data, displayIndex) {//行定义
                if (data.ParentId != "0") {
                    $(row).attr("class", "text-c treegrid-" + data.PowerId + " treegrid-parent-" + data.ParentId);
                } else {
                    $(row).attr("class", "text-c treegrid-" + data.PowerId);
                }
            },

就是来控制父子关系的。

而后台的List顺序转换,是为了调整好输出的顺序,从而来控制tr之间的位置关系。

通过DT初始化好表格之后,调用

$("#table1").treegrid({
                    "initialState": 'collapsed',
                });

即可,绘制好树状表格。

效果图:

热门栏目