public CategoryTree GetChildCategory(CategoryTree category, int?parentId) { var childCategory = db.Category.Where(en => en.parentId == parentId).OrderBy(en => en.sort).ToList(); if (childCategory.Count == 0) { return(null); } List <CategoryTree> lstCategory = new List <CategoryTree>(); childCategory.ForEach(child => { var nCategory = new CategoryTree() { id = child.id, title = child.title, parentId = child.parentId, parentName = child.parentName, sort = child.sort, select = string.Empty }; GetChildCategory(nCategory, child.id); lstCategory.Add(nCategory); }); if (lstCategory != null) { category.children = lstCategory; } return(category); }
public IHttpActionResult GetCategory(int type) { ResultData result = new ResultData(); try { var lstCategory = db.Category.Where(en => en.type == type && en.parentId == null).OrderBy(en => en.sort.Trim()).ToList(); if (lstCategory.Count == 0) { return(ErrorResult(ResultCode.Successed, "暂无数据.")); } List <CategoryTree> lstCategoryTree = new List <CategoryTree>(); lstCategory.ForEach(item => { var child = new CategoryTree(); child.id = item.id; child.title = item.title; child.parentId = item.parentId; child.parentName = item.parentName; child.sort = item.sort; child.select = string.Empty; var childCategory = GetChildCategory(child, item.id); if (childCategory == null) { lstCategoryTree.Add(child); } else { lstCategoryTree.Add(childCategory); } }); result.code = (int)ResultCode.Successed; result.data = JsonConvert.SerializeObject(lstCategoryTree); } catch (Exception ex) { result = new ResultData { code = (int)ResultCode.Faild, msg = ex.Message }; } return(Json(result)); }