由于日常WEB开发中常会用到树形来完成以下主要功能。
主要解决以下一些功能
- 数据结构的树形层级展示
- 多选项目
- 单选项目
- 方便Ajax延迟加载
经过几个插件的比较最后决定使用dynatree。来完成以上功能。
dynatree项目网站 https://code.google.com/p/dynatree/
本文中dynatree的版本为1.2.4
首先通常代码中会有一个树形结构的实体对象如下代码:
- public class Node
- {
- public int ID { get; set; }
-
- public string Name { get; set; }
-
- public string Description { get; set; }
-
- public List<Node> Children { get; set; }
-
- public Node Parent { get; set; }
- }
由于我们采用AJAX方式所以我打算在后台的controller中返回json的方式来完成对tree的数据加载
于是为了方便dynatree的前台接受,我做了一个封装类代码如下
- public class DynatreeNode
- {
- private DynatreeNode()
- {
- children = new List<DynatreeNode>();
- }
-
- #region property
-
-
-
- public string title { get; set; }
-
-
-
-
- public string tooltip { get; set; }
-
-
-
-
- public string href { get; set; }
-
-
-
-
- public string icon { get; set; }
-
-
-
-
- public string addClass { get; set; }
-
-
-
-
- public List<DynatreeNode> children { get; set; }
-
-
-
-
- public bool unselectable { get; set; }
-
-
-
-
- public bool hideCheckbox { get; set; }
-
-
-
-
- public bool select { get; set; }
-
-
-
-
- public string key { get; set; }
-
-
-
-
- public bool expand { get; set; }
-
-
-
-
- public bool focus { get; set; }
-
-
-
-
- public bool isFolder { get; set; }
-
-
-
-
- public bool isLazy { get; set; }
-
-
-
-
- public bool noLink { get; set; }
-
-
-
-
- public bool activate { get; set; }
- #endregion
-
- public static DynatreeNode Create(Node node)
- {
- DynatreeNode dynatreeNode = new DynatreeNode
- {
- title = node.Name,
- tooltip = node.Name,
- activate = false,
- addClass = null,
- expand = false,
- focus = false,
- icon = null,
- href = null,
- key = null,
- unselectable = false,
- select = false,
- noLink = false,
- isLazy = false,
- hideCheckbox = false,
- isFolder = false
- };
- foreach (var item in node.Children)
- {
- dynatreeNode.isFolder = true;
- dynatreeNode.children.Add(DynatreeNode.Create(item));
- }
- return dynatreeNode;
- }
- }
因为javascript对大小写敏感所以这里我将属性都改成小写已达到和dynatree的children参数统一。
接下来控制器很简单的返回json即可,代码如下:
- public ActionResult AjaxTree()
- {
- root = GetTreeRoot();
- var dynatreeNode = DynatreeNode.Create(root);
- return Json(dynatreeNode, JsonRequestBehavior.AllowGet);
- }
在view视图中我们只要加载jquery,jqueryUI和dynatree.js
由于dynatree的checkbox等使用样式写的,所以也必须引用dynatree.css
视图view的代码如下:
- @{
- ViewBag.Title = "Index";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
- <h3>Index</h3>
- <div id="tree"></div>
- @section scripts{
- <link href="~/Content/skin-vista/ui.dynatree.css" rel="stylesheet" />
- <script src="~/Scripts/jquery.dynatree.js"></script>
- <script type="text/ecmascript">
- $(function () {
- $("#tree").dynatree({
- checkbox: true,
- selectMode: 2,
- initAjax: { url: '/home/ajaxTree' },
- onSelect: function (select, node) {
- if (select) {
- alert(node.data.title)
- }
- }
- });
- });
- </script>
- }
一颗简单的多选树就这么完成了,如果要单选只需将参数selectMode设置为1