MVC 中 Razor 无限分类的展示
生活随笔
收集整理的這篇文章主要介紹了
MVC 中 Razor 无限分类的展示
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在MVC的Razor視圖展示無級分類的辦法,在網(wǎng)上看了很多資料,大多搞得很高大上。可能本人水平有限,實在是不會用。
那我就用最簡單爆力的辦法來做。
Model:
public class NewsCategory{[Key]public int CategoryId { get; set; }public int ParentCategoryId { get; set; }[Required][StringLength(50)]public string CategoryName { get; set; }}ViewModel
public class NewsCategoriesViewModel{public int Id { get; set; }public string Name { get; set; }public List<NewsCategoriesViewModel> children { get; set; }}Controller
遞歸獲取數(shù)據(jù),然后返回給視圖
1 abcContext db = newabcContext(); 2 public ActionResult Index() 3 { 4 var categoryList = GetCategoryList(0); 5 return View(categoryList); 6 } 7 8 [NonAction] 9 public List<NewsCategoriesViewModel> GetCategoryList(int Id) 10 { 11 List<NewsCategoriesViewModel> uvModel = new List<NewsCategoriesViewModel>(); 12 13 14 var perentList = db.Set<NewsCategory>().Where(p => p.ParentCategoryId == Id).ToList(); 15 16 if (perentList.Count > 0) 17 { 18 foreach (var item in perentList) 19 { 20 NewsCategoriesViewModel userViewModel = new NewsCategoriesViewModel 21 { 22 Id = item.CategoryId, 23 Name = item.CategoryName, 24 children = new List<NewsCategoriesViewModel>() 25 }; 26 List<NewsCategoriesViewModel> tempList = GetCategoryList(item.CategoryId); 27 if (tempList.Count > 0) 28 { 29 //這里出錯了; 30 //userViewModel.children.Add(tempList); 31 userViewModel.children = tempList; 32 } 33 uvModel.Add(userViewModel); 34 } 35 } 36 return uvModel; 37 } 38 }View
定義一個視圖方法,然后遞歸調(diào)用。
@model List<NewsCategoriesViewModel> @helper DisplayList(List<NewsCategoriesViewModel> model){if (model.Count > 0){<ul>@foreach (var item in model){<li>@item.Name</li>if (item.children.Count > 0){@DisplayList(item.children);}}</ul>}}@DisplayList(Model)打完收功!
轉(zhuǎn)載于:https://www.cnblogs.com/micenote/p/5032497.html
總結(jié)
以上是生活随笔為你收集整理的MVC 中 Razor 无限分类的展示的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UIApplication,UIWind
- 下一篇: Android NDK开发一:配置环境