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

上一篇介绍了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");
 }
}
<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
 <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
 <title>用户列表</title>
 <link href="~/Content/Scripts/h-ui/css/H-ui.min.css" rel="stylesheet" />
 <link href="~/Content/Scripts/h-ui.admin/css/H-ui.admin.css" rel="stylesheet" />
 <link href="~/Content/Scripts/Hui-iconfont/1.0.8/iconfont.css" rel="stylesheet" />
 <link href="~/Content/Scripts/treegrid/css/jquery.treegrid.css" rel="stylesheet" />
 <style>
 .page-container {
  padding: 10px;
 }
 .operation {
  background: #EFEEF0;
  padding: 3px;
 }
 .search {
  background: #EFEEF0;
  padding: 5px;
  margin-top: 5px;
 }
 .table {
  margin-top: 10px;
 }
 .dataTables_info {
  margin-left: 5px;
 }
 #table1_info {
  padding: 0;
 }
 #table1_length {
  margin-left: 15px;
 }
 </style>
 <!--引入脚本解决兼容性(hack技术,必须放入head中)-->
 <!--[if lt IE 9]>
 <script src="~/Content/Scripts/html5_css3/html5shiv.min.js"></script>
 <script src="~/Content/Scripts/html5_css3/respond.min.js"></script>
 <script src="~/Content/Scripts/PIE-2.0beta1/PIE_IE678.js"></script>
 <![endif]-->
</head>
<body>
 <div class="page-container">
 <div class="operation">
  @Html.Partial("CRUDBtn", userInfo)
 </div>

 <div class="table">
  <table id="table1" class="table table-border table-bordered table-bg table-hover">
  <thead>
   <tr class="text-c">
   <th><input type="checkbox" name="" value=""></th>
   <th>菜单名</th>
   <th>请求路径</th>
   <th>描述</th>
   <th>添加时间</th>
   <th>修改时间</th>
   </tr>
  </thead>
  </table>
 </div>
 </div> 
</body>
</html>
<script src="~/Content/Scripts/jquery-2.0.3.min.js"></script>
<script src="~/Content/Scripts/datatables/1.10.13/jquery.dataTables.min.js"></script>
<script src="~/Content/Scripts/layer/2.1/layer.js"></script>
<script src="~/Content/Scripts/My97DatePicker/WdatePicker.js"></script>
<script src="~/Content/Scripts/h-ui/js/H-ui.js"></script>
<script src="~/Content/Scripts/h-ui.admin/js/H-ui.admin.js"></script>
<script src="~/Content/Scripts/treegrid/js/jquery.treegrid.min.js"></script>
<script type="text/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 "<input type='checkbox' value='" + data + "' name='id'>";
   }
  },
  {
   "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;
    var date = 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 {
    var dateTime = new Date(parseInt(data.replace("/Date(", "").replace(")/", ""), 10));
    var month = dateTime.getMonth() + 1 < 10 ? "0" + (dateTime.getMonth() + 1) : dateTime.getMonth() + 1;
    var date = 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;
 }
</script>

后台:

public ActionResult Search(DataTable dt)
 {
 int total;
 IQueryable<Model.Power> powerIq = CurrentBllSession.PowerBll.GetIQueryable();
 total = powerIq.Count();
 List<Model.Power> powerList = powerIq.ToList();
 powerList = TreeGridList(powerList);
 dt.recordsTotal = total;
 dt.recordsFiltered = total;
 dt.data = powerList;
 return Json(dt);
 }
 /// <summary>
 /// 将List转换为TreeGrid格式的List
 /// </summary>
 private List<Model.Power> TreeGridList(List<Model.Power> powerList)
 {
 List<Model.Power> treegridList=new List<Model.Power>();
 foreach (var powerOne in powerList.Where(a => a.ParentId == "0" || a.PowerId.Length == 4).OrderBy(a => a.Sort))//一级菜单
 {
 treegridList.Add(powerOne);
 foreach (var powerTwo in powerList.Where(a => a.ParentId != "0" && a.PowerId.Length == 8 && a.ParentId == powerOne.PowerId).OrderBy(a=>a.Sort))//二级菜单
 {
  treegridList.Add(powerTwo);
  foreach (var powerBtn in powerList.Where(a => a.ParentId != "0" && a.PowerId.Length == 8 && a.ParentId == powerTwo.PowerId).OrderBy(a => a.Sort))//按钮
  {
  treegridList.Add(powerBtn);
  }
 }
 }
 return treegridList;
 }

解释说明:

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',
    });

即可,绘制好树状表格。

效果图:

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持菜鸟教程(cainiaojc.com)!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#cainiaojc.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。