控制器:
1 /// <summary> 2 /// 树初始化 3 /// </summary> 4 /// <returns></returns> 5 [HttpPost] 6 public ContentResult InitTree() 7 { 8 List<TestModel> items = bll.GetTreeFormList(); 9 Action<TestModel> SetChildren = null; 10 //封装一个方法(递归)不断读取树的分支 11 SetChildren = Parent => 12 { 13 Parent.Children = items.Where(childItem => childItem.ParentGuid == Parent.Guid).ToList(); 14 Parent.Children.ForEach(SetChildren); 15 }; 16 //初始化树列表 17 List<TestModel> treeItems = items.Where(rootItem => rootItem.ParentGuid == "").ToList(); 18 treeItems.ForEach(SetChildren); 19 20 string strJson = JsonConvert.SerializeObject(treeItems, 21 Formatting.Indented, 22 new JsonSerializerSettings() 23 { 24 NullValueHandling = NullValueHandling.Ignore, 25 ReferenceLoopHandling = ReferenceLoopHandling.Ignore, 26 Converters = new List<JsonConverter> { new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" } } 27 }).Replace("Children", "children"); 28 29 return Content(strJson); 30 }
实体:
1 public class TestModel 2 { 3 public string Guid { get; set; } 4 public string Name { get; set; } 5 public string Price { get; set; } 6 public string ParentGuid { get; set; } 7 8 public List<TestModel> Children { get; set; } 9 }
时间: 2024-11-15 22:16:00