Views代码

@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/content/js/plugins/jsTree/jstree.min.js"></script>
</head>
<body>
<div id="using_json"></div>
<script>
$(document).ready(function () {
@{
var a = new HtmlString(ViewBag.Region);//将动态数据转换成HTMLstring格式
}
$("#using_json").jstree(@a);//jsTree绑定数据
});
</script>
</body>
</html>

Controller代码

        public ActionResult Index()
{
RegionModels list = new RegionModels();
list.region = service.GetRegion();//查询区域数据
list.dormcategory = service.GetDormCategory();//获取宿舍类型
RegionModel region = service.GetSingleRegion("");
ViewBag.Region = GetRegionJson(region.Cid, list.region);
return View(list);
}
/// <summary>
/// 返回jsTree的最外层值
/// </summary>
/// <param name="parentid">父级Cid</param>
/// <param name="data">数据</param>
/// <returns></returns>
public string GetRegionJson(string parentid, List<RegionModel> data)
{
string icon = GetIcon();
string a = "{\"core\": {\"themes\": {\"theme\": \"classic\",\"dots\": true},\"data\":[{\"text\":\"区域\",\"icon\": \""+icon+"\",\"id\":\"" + parentid + ",0\",\"state\": {\"opened\": true },\"children\":[";
StringBuilder sb = new StringBuilder(a);
RegionList(parentid, data, sb);//添加子集数据
sb.Append("]}]}}");
return sb.ToString();
}
/// <summary>
/// 添加jsTree子集数据
/// </summary>
/// <param name="parentid"></param>
/// <param name="list"></param>
/// <param name="sb"></param>
public void RegionList(string parentid, List<RegionModel> list, StringBuilder sb)
{
IEnumerable<RegionModel> temp = list.Where(n => n.ParentCid.Trim() == parentid).OrderBy(r => r.Name);
foreach (var item in temp)
{
string open = item.Level == ? "true" : "false";
string icon = GetIcon(item.Level);
string lastComma = "";
if (item != temp.Last())
lastComma = ",";
List<RegionModel> children = list.Where(n => n.ParentCid.Trim() == item.Cid).ToList();
if (children.Count == )
{
sb.Append($" {{ \"text\": \"{item.Name}\",\"icon\": \"{icon}\",\"id\":\"{ item.Cid.ToString() + "," + item.Level.ToString()}\",\"state\": {{\"opened\": {open} }},}}{lastComma}");
}
else
{
sb.Append($" {{\"text\": \"{item.Name}\",\"icon\": \"{icon}\",\"id\":\"{ item.Cid.ToString() + "," + item.Level.ToString()}\",\"state\": {{\"opened\": {open} }},");
sb.Append("\"children\": [");
RegionList(item.Cid, list, sb);
sb.Append($"]}}{lastComma}");
}
}
}

结果

jsTree动态加载数据-LMLPHP

04-30 06:36