首先引入文件:
<link href="./css/bootstrap.css" rel="stylesheet">
<script src="./js/jquery.js"></script>
<script src="./js/bootstrap-treeview.js"></script>
HTML 结构:
<div id="tree"></div> //不一定是div元素 其他也可以。在这我用的div演示
调用插件Treeview方法:
<script>
$(function () {
$('#tree').treeview({
color: "#428bca",
data: getDept(), //Treeview的数据源 返回json
levels: 4,
onNodeSelected: function (e, m) { //Treeview 被选中事件
var id=m.tags[0];
var remark=m.text;
},
onNodeUnselected: function (e, m) { //Treeview 取消选中事件
}
})
});
</script>
//Treeview数据源方法
function getDept() {
var exc = "";
$.ajax({
type: "post",
url: "@Url.Action("getList", "Home")",
async: false,
datatype: "json",
success: function (data) {
if (!data.result) {
alert("出现异常");
return;
}
exc = data.data;
}
});
return exc;
}
Controllers层:
public JsonResult getList()
{
////查询列表
IList<TreeView> List = TreeViewService.GetDeptList(-); //最高部门的父id是-1
var jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; //忽略空值
string json = JsonConvert.SerializeObject(List, Formatting.Indented,jSetting);
return Json(new { result = true, data = json });
}
Dal层:
public static IList<TreeView> GetDeptList(int SuperiorID = )
{
DataTable dt = SqlHelper.FillSqlDataTable("SELECT DeptName AS text,CONVERT(VARCHAR(10),ID)+','+DeptCode+','+ISNULL(Remark,'') AS tags,'' AS href FROM dbo.Sys_Dept WHERE State=0 and SuperiorID=" + SuperiorID); return GetListByTable(dt);
}
//将Datable转成list
private static IList<TreeView> GetListByTable(DataTable dt, int kind = )
{
IList<TreeView> list = new List<TreeView>();
if (dt != null && dt.Rows.Count > )
{
foreach (DataRow row in dt.Rows)
{
TreeView model = new TreeView(); if (row["tags"] != null)
{
model.tags = row["tags"].ToString().Split(',');
}
if (row["text"] != null)
{
model.text = row["text"].ToString();
}
if (dt.Columns.Contains("href") && row["href"].ToString().Trim() != null)
{
model.href = row["href"].ToString();
}
if (kind == )
{
//部门的Treeview
model.nodes = GetDeptList(int.Parse(model.tags[]));
}
if (kind == )
{
//菜单的Treeview
model.nodes = GetMenusList(int.Parse(model.tags[]));
}
list.Add(model);
}
return list;
}
return null;
}
Model 层:
//bootstrap的treeview插件返回数据源json格式必须是下面这样的,所以在写sql语句时就要用 as 重命名字段,往上翻看我的sql语句就会明白。
public class TreeView
{
public string icon { get; set; }
public string text { get; set; }
public string[] tags { get; set; }
public string href { get; set; }
public IList<TreeView> nodes { get; set; }
}