mvc2中如何在下拉列表中显示含有子类的项(子类前加--)
生活随笔
收集整理的這篇文章主要介紹了
mvc2中如何在下拉列表中显示含有子类的项(子类前加--)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如果要得到包含子類的項,理所當然要用到遞歸。下面的這個例子是在下拉列表中獲取所有部門
? helper中代碼如下:
1 /// <summary> 2 /// 循環獲取部門 3 /// </summary> 4 /// <param name="list"></param> 5 /// <param name="deptId"></param> 6 /// <param name="grade"></param> 7 private void LoopGetDept(IList<Dept> list, int deptId, int grade) 8 { 9 IList<Dept> items = DeptHelper.GetListsByParentId(deptId); 10 string sp = ""; 11 for (int i = 0; i < grade; i++) 12 { 13 sp += "--"; 14 } 15 if (items.Count > 0) 16 { 17 for (int i = 0; i < items.Count; i++) 18 { 19 items[i].DeptName = sp + items[i].DeptName; 20 list.Add(items[i]); 21 LoopGetDept(list, items[i].DeptID, grade + 1); 22 } 23 } 24 } /// <summary>/// 根據父id取子記錄,不分頁/// </summary>/// <param name="id"></param>/// <returns></returns>public static IList<Dept> GetListsByParentId(int id){using (UUMContext uc = new UUMContext()){var dept = from a in uc.Depts select a;if (id >= 0){dept = dept.Where(a => a.DeptParent == id);}IList<Dept> list=dept.ToList<Dept>();return list;}}?
/// <summary>/// 得到上級部門列表/// </summary>/// <returns></returns>public IList<Dept> GetAllListForSel(){IList<Dept> list = new List<Dept>();LoopGetDept(list, 0, 0);list.Insert(0, new Dept() { DeptID = 0, DeptName = "根" });return list;}?
然后在controller中綁定數據即可。
?ViewData["DeptParent"] = new SelectList(deptHelper.GetAllListForSel(), "DeptID", "DeptName");
轉載于:https://www.cnblogs.com/SunYiwei/archive/2012/05/23/2514916.html
總結
以上是生活随笔為你收集整理的mvc2中如何在下拉列表中显示含有子类的项(子类前加--)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 路
- 下一篇: QTP自动化测试视频系列