diff --git a/CoreCms.Net.Model/ViewModels/DTO/WxGoodCategoryDto.cs b/CoreCms.Net.Model/ViewModels/DTO/WxGoodCategoryDto.cs index d9ef072a..f7c88477 100644 --- a/CoreCms.Net.Model/ViewModels/DTO/WxGoodCategoryDto.cs +++ b/CoreCms.Net.Model/ViewModels/DTO/WxGoodCategoryDto.cs @@ -35,29 +35,6 @@ namespace CoreCms.Net.Model.ViewModels.DTO /// public string imageUrl { get; set; } - public List child { get; set; } - } - - public class WxGoodCategoryChild - { - /// - /// 序列 - /// - public int id { get; set; } - - /// - /// 标题 - /// - public string name { get; set; } - - /// - /// 排序 - /// - public int sort { get; set; } - - /// - /// 图片地址 - /// - public string imageUrl { get; set; } + public List? child { get; set; } } } \ No newline at end of file diff --git a/CoreCms.Net.Web.WebApi/Controllers/GoodController.cs b/CoreCms.Net.Web.WebApi/Controllers/GoodController.cs index 2c37efc1..5eef1832 100644 --- a/CoreCms.Net.Web.WebApi/Controllers/GoodController.cs +++ b/CoreCms.Net.Web.WebApi/Controllers/GoodController.cs @@ -109,46 +109,39 @@ namespace CoreCms.Net.Web.WebApi.Controllers var jm = new WebApiCallBack() { status = true }; var data = await _goodsCategoryServices.QueryListByClauseAsync(p => p.isShow == true, p => p.sort, OrderByType.Asc, true, true); - var wxGoodCategoryDto = new List(); - var parents = data.Where(p => p.parentId == 0).ToList(); - if (parents.Any()) - { - parents.ForEach(p => - { - var model = new WxGoodCategoryDto - { - id = p.id, - name = p.name, - imageUrl = !string.IsNullOrEmpty(p.imageUrl) ? p.imageUrl : "/static/images/common/empty.png", - sort = p.sort - }; - - var childs = data.Where(p => p.parentId == model.id).ToList(); - if (childs.Any()) - { - var childsList = new List(); - childs.ForEach(o => - { - childsList.Add(new WxGoodCategoryChild() - { - id = o.id, - imageUrl = !string.IsNullOrEmpty(o.imageUrl) ? o.imageUrl : "/static/images/common/empty.png", - name = o.name, - sort = o.sort - }); - }); - model.child = childsList; - } - wxGoodCategoryDto.Add(model); - }); - } jm.status = true; - jm.data = wxGoodCategoryDto; + jm.data = GetCategories(data, 0); return jm; } + /// + /// 迭代方法 + /// + /// + /// + /// + private static List GetCategories(List oldCategories, int parentId) + { + List childTree = new List(); + var model = oldCategories.Where(p => p.parentId == parentId).ToList(); + foreach (var item in model) + { + var parentTree = new WxGoodCategoryDto(); + parentTree.id = item.id; + parentTree.imageUrl = !string.IsNullOrEmpty(item.imageUrl) ? item.imageUrl : "/static/images/common/empty.png"; + parentTree.name = item.name; + parentTree.sort = item.sort; + + childTree.Add(parentTree); + + parentTree.child = GetCategories(oldCategories, item.id); + } + return childTree; + } + + #endregion #region 根据查询条件获取分页数据============================================================