• 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

  • 相关阅读:
    Luogu P2495 [SDOI2011]消耗战
    40. Combination Sum II
    39. Combination Sum
    22. Generate Parentheses
    51. N-Queens
    Codeforces Round #346 (Div. 2) E. New Reform
    Codeforces Round #346 (Div. 2) D. Bicycle Race
    HDU 5651xiaoxin juju needs help
    VK Cup 2016
    Educational Codeforces Round 10 D. Nested Segments
  • 原文地址:https://www.cnblogs.com/jorzen1984/p/6602448.html
Copyright © 2020-2023  润新知