本文支持两种方式的数据,一种为List集合,一种为json字符串。
先来介绍一下后台返回list集合(推荐使用此方法):
控制器代码如下:
public static ListDInfo = new List (); /// /// TreeView视图 /// ///public ActionResult May(string TypeCode,int parentId) { ViewBag.TypeCode = TypeCode; ViewBag.ParentId = parentId; return View(); } [HttpPost] public ActionResult GetTreeData(string TypeCode,int parentId) { List DInfo = dbll.GetModelList("TypeCode="+TypeCode); return Json(GetChildNodes(0,new NodeModel(){}, DInfo).nodes); } /// /// GetChildNodes方法,此方法使用递归 /// /// ///public NodeModel GetChildNodes(int parentId,NodeModel childnodestr,List DInfo) { List DictionaryList = DInfo.Where(e => Convert.ToInt32(e.ParentId) == parentId).ToList(); for (int i = 0; i < DictionaryList.Count; i++) { NodeModel NewNode = new NodeModel(); NewNode.DicId = DictionaryList[i].DicId; NewNode.text = DictionaryList[i].DICName; NewNode.ParentId = DictionaryList[i].ParentId; childnodestr.nodes.Add(NewNode); GetChildNodes(NewNode.DicId, NewNode, DInfo); } return childnodestr; }
视图代码如下: