jstree的数据后台生成
jstree在前台的HTML格式如:
<div id="demo1" class="demo" style="height:100px;">
<ul> <li id="phtml_1"> <a href="#">Root node 1</a> <ul> <li id="phtml_2"> <a href="#">Child node 1</a> </li> <li id="phtml_3"> <a href="#">Child node 2</a> </li> </ul> </li> <li id="phtml_4"> <a href="#">Root node 2</a> </li> </ul> </div>
后台生成这种格式的数据:(无限级,递归)
private string GetTreeString(int pid)
{ IEnumerable<Model.TreesModel> TreesModelList= TreesBLL.GetList(); return "<ul>" + AddTreeNodeString(0, "所有栏目", customClassList) + "</ul>"; }private string AddTreeNodeString(int nodeId, string nodeName, IEnumerable<Model.TreesModel> list)
{ string nodeString = "";//找出List 中以nodeId为ParentID的节点
IEnumerable<Model.TreesModel> childNodes = list.Where(i => i.PId== nodeId).OrderBy(i => i.SortNumber);int nodeCount = childNodes.Count();
if (nodeCount == 0)
{ //如果没找到子节点,返回<li></li> nodeString = "<li><a href='#'>" + nodeName + "</a></li>"; } else { //如果找到子节点,增加<ul> nodeString = "<li><a href='#'>" + nodeName + "</a><ul>";//按子节点循环,每次掉自己增加一个节点的nodeString
foreach (var item in childNodes) { nodeString += AddTreeNodeString(item.Id, item.Name, list); } //增加</ul> nodeString += "</ul></li>"; }return nodeString;
}