如果数据库中存在的department部门表,其中ID为主键,PID为父类,Name为部门名称,设计如下:
- public class department
- {
- public int ID { get; set; }
- public int PID { get; set; }
- public string Name { get; set; }
- }
- private string departmentRecursion(int pid, List<department> obj)
- {
- string a = "<dl style='margin:0px;padding:0px;'>";
- for (int i = 0; i < obj.Count; i++)
- {
- if (obj[i].PID == pid)
- {
- a += "<dt style='border-bottom:1px solid #808080'>" + obj[i].Name + "</dt>\n<dd>" + departmentRecursion(obj[i].ID, obj) + "</dd>";
- }
- }
- a += "</dl>";
- return a;
- }
- public ActionResult Index()
- {
- return View();
- }
- public ActionResult DeparTmentList()
- {
- List<department> ds = new List<department>()
- {
- new department(){ ID=6, Name="前端开发组1", PID=4},
- new department(){ ID=1, Name="XX公司", PID=0},
- new department(){ ID=2, Name="开发部", PID=1},
- new department(){ ID=3, Name=".NET开发部门", PID=2},
- new department(){ ID=5, Name=".NET开发组1", PID=3},
- new department(){ ID=4, Name="前端开发部门", PID=2},
- new department(){ ID=6, Name=".NET开发组2", PID=3},
- };
- return Content(departmentRecursion(0, ds));
- }
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
- </head>
- <body>
- @Html.Action("DeparTmentList", "Home");<span style="white-space:pre"> </span>
- </body>
- </html>
使用JS树形递归,部门树状图:
- <script>//数据结构
- var json = [
- { id: 1, pid: 0, text: '1(XX公司)' },
- { id: 2, pid: 4, text: '2.1.1(开发部a-1组)' },
- { id: 3, pid: 0, text: '2(开发部)' },
- { id: 4, pid: 3, text: '2.1(开发部a)' },
- { id: 5, pid: 0, text: '3(人事部)' },
- { id: 6, pid: 5, text: '3.1(人事部A)' },
- { id: 7, pid: 0, text: '4(设计部)' },
- { id: 8, pid: 7, text: '4.1(设计部A)' },
- { id: 9, pid: 4, text: '2.1.2(开发部a-2组)' },
- { id: 11, pid: 2, text: '2.1.1.1(开发部a-1组>1小组)' },
- { id: 12, pid: 2, text: '2.1.1.2(开发部a-1组>2小组)' },
- { id: 13, pid: 5, text: '3.2(人事部A)' },
- { id: 19, pid: 5, text: '3.3(人事部B)' }
- ];
- function departmentRecursion(mid, obj) {
- var a = '<dl>';
- for (var i = 0, j; j = obj[i++];)
- if (j.pid == mid)
- a += '<dt>' + j.text + '</dt><dd>' + departmentRecursion(j.id, obj) + '</dd>'
- a += '</dl>';
- return a;
- }
- document.write(departmentRecursion(0, json));
- </script>