bootstrap的treeview使用方法


首先引入文件:

<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(-1);  //最高部門的父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 = 0)
        {
            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 = 0) { IList<TreeView> list = new List<TreeView>(); if (dt != null && dt.Rows.Count > 0) { 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 == 0) { //部門的Treeview model.nodes = GetDeptList(int.Parse(model.tags[0])); } if (kind == 1) { //菜單的Treeview model.nodes = GetMenusList(int.Parse(model.tags[0])); } 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; } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM