1、参考资料
2、相关代码
- 前端
-
<input id="DeptId" name="DeptId" value="请选择" /> Id对应Model中需要生成的数据编号,如需生成部门combotree,属性为DeptId2、 $(document).ready(function () {$('#DeptId').combotree({url: '@Url.Action("GetTree", "Dept")',//选择树节点触发事件onSelect: function (node) {//返回树对象var tree = $(this).tree;//选中的节点是否为叶子节点,如果不是叶子节点,清除选中var isLeaf = tree('isLeaf', node.target);if (!isLeaf) {//清除选中$('#DeptId').combotree('clear');}}});$('#DeptId').combotree('setValue',@Model.DeptId==0?'':@Model.DeptId);});
- 后台
public ActionResult GetTree(){var list =获取包含两级关系的数据,可自行扩展成多级;var result = new List<JsonTreeNode>();foreach (var fac in list){var facNode = new JsonTreeNode(); //一级节点facNode.id = "";facNode.text = fac.FactoryName;facNode.@checked = "disabled";var depChildren = new List<JsonTreeNode>();var depList =//获取一级节点下的二级节点数据;if (depList.Count() > 0){foreach (var dep in depList){JsonTreeNode depNode = new JsonTreeNode();depNode.id = dep.DepId.ToString();depNode.text = dep.DepName;depNode.@checked = "disabled";depChildren.Add(depNode);}facNode.children = depChildren;result.Add(facNode);}}return Json(result);}
3、注意事项
- 前端代码必须先后执行,如果在第一个combotree()添加setValue设置,则无效
$('#DeptId').combotree() $('#DeptId').combotree('setValue',@Model.DeptId==0?'':@Model.DeptId); //加载时默认选择 - onSelect设置为选择非叶子节点时则清空数据