首先是定义类,这里我有两个表,使用用到了类的继承
这是第一个类(如果你只用到一张表,就像这个类这样写就好了)
public class company_rubbish_manage_type_link_ext: company_rubbish_manage_type
{
public int RubbishTypeId { get; set; }
public int CompanyId { get; set; }
public string user_name { get; set; }
//这个是必须的,用来记录子级
public List<company_rubbish_manage_type_link_ext> children = new List<company_rubbish_manage_type_link_ext>();
}
第二个类
public class company_rubbish_manage_type
{
public int Id { get; set; }
public string Name { get; set; }
//这个title一定要,这是layui显示树形组件下拉列表的标题值
public string title { get; set; }
public string Code { get; set; }
public int Type { get; set; }
public int Grade { get; set; }
public int ParentId { get; set; }
public int OperatorId { get; set; }
public DateTime CreateTime { get; set; }
}
然后就是定义递归的方法,我下面有两种写法,都能实现相要的效果
首先从数据库查出来的数据列表如下,里面一定要有父级Id(parentId)和自己的Id,我这里parentId为0就是最大的父级
第一种方法没用递归,也比较简单
public JsonResult GetCompanyRubbishManageTypeByLinkId()
{
//这个是你从数据库查出来的数据列表的方法
List<company_rubbish_manage_type_link_ext> list = _companyRubbishManageTypeLinkServices.GetExistList(compa