C#无限极分类菜单方法

话不多说直接上代码

我利用的是MVC5+EF做的。

以下这部分是controller代码。


public JsonResult Test() { List<Category> Categorylist = GetAllCategorys(); Category root = db.Categorys.Find(1); LoopToAppendChildren(root); return Json(root.ChildCategory, JsonRequestBehavior.AllowGet); } public void LoopToAppendChildren(Category curItem) { var subItems = GetCategorys(curItem.ID); curItem.ChildCategory = new List<Category>(); curItem.ChildCategory.AddRange(subItems); foreach (var subItem in subItems) { LoopToAppendChildren(all, subItem); } } public List<Category> GetCategorys(int ParentID) { var categorys = from s in db.Categorys orderby s.ID descending where s.CategoryParentID == ParentID select s; return categorys.ToList(); } public List<Category> GetAllCategorys() { var categorys = from s in db.Categorys orderby s.ID descending select s; return categorys.ToList(); }

 这部分是Category类代码

 public class Category
    {
        public int ID { get; set; }
        public string CategoryName { get; set; }
        public string CategoryInfo { get; set; }
        public int CategoryParentID { get; set; }
        public bool CategoryStatus { get; set; }
        public int CategorySort { get; set; }
        public List<Category> ChildCategory { get; set; }
    }

 

主要就是这两个文件,此部分可以用于bootstrap treeview的使用,和面包屑导航栏的使用。

 

//通用 ParentId,Id,children 用了反射效率不高,没测试

public void LoopToAppendChildren<T>(List<T> all, T curItem, string parentIdName = "ParentId", string idName = "Id", string childrenName = "children")
{
  var subItems = all.Where(ee => ee.GetType().GetProperty(parentIdName).GetValue(ee, null).ToString() == curItem.GetType().GetProperty(idName).GetValue(curItem, null).ToString()).ToList(); //新闻1

  curItem.GetType().GetField(childrenName).SetValue(curItem, subItems);
  foreach (var subItem in subItems)
  {
    LoopToAppendChildren(all, subItem);//新闻1.1
  }
 }

 

参考文章:http://www.cnblogs.com/xuejianxiyang/p/5027280.html

 

posted @ 2017-03-22 22:22  初雪  阅读(1785)  评论(0编辑  收藏  举报