asp.net mvc easyui tree

1、html页面代码:  

<div class="easyui-panel" style="padding:5px" id="powerTree">            
        </div>

2、js代码:

需要返回数据格式如下:

[
{"id":1,"parendId":0,"name":"123"},
{"id":2,"parentId":1,"name":"456"},
{"id":3,"parentId":1,"name":"789"},
{"id":4,"parentId":2,"name":"444444"},
]

代码如下:

$('#powerTree').tree({
            url: '/Sys/GetRolePower',
            method: 'post',
            checkbox: false,//定义是否在每个节点前边显示复选框
            onBeforeLoad: function (node, param) {
                param.id = id //传参数
            },
            loadFilter: function (rows) {
                return convert(rows.data);
            },
            onLoadError: function (ex) {
                $.messager.alert('消息', "加载失败", 'error');
            }
        });



function convert(rows) {
        rows = JSON.parse(rows);//json转对象

        function exists(rows, parentId) {
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].id == parentId) return true;
            }
            return false;
        }

        var nodes = [];
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            if (!exists(rows, row.parentId)) {
                nodes.push({
                    id: row.id,
                    text: row.name
                });
            }
        }

        var toDo = [];
        for (var i = 0; i < nodes.length; i++) {
            toDo.push(nodes[i]);
        }
        while (toDo.length) {
            var node = toDo.shift();
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                if (row.parentId == node.id) {
                    var child = { id: row.id, text: row.name };
                    if (node.children) {
                        node.children.push(child);
                    } else {
                        node.children = [child];
                    }
                    toDo.push(child);
                }
            }
        }
        return nodes;
    }

 

3、后端代码:

[HttpPost]
        public JsonResult GetRolePower()
        {
            int roleId = Convert.ToInt32(HttpContext.Request.Form["id"]);

            var treeList = GetData(roleId);
            var roleTree = from item in treeList
                                select new
                                {
                                    id = item.id,
                                    parentId = item.pId,
                                    name = item.Name
                                };
            var data = JsonConvert.SerializeObject(roleTree);

            return Json(new { data }, JsonRequestBehavior.AllowGet);
        }

 

posted @ 2018-05-22 19:32  一夜秋2014  Views(708)  Comments(0Edit  收藏  举报