日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

MVC 中 Razor 无限分类的展示

發布時間:2024/8/26 c/c++ 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MVC 中 Razor 无限分类的展示 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在MVC的Razor視圖展示無級分類的辦法,在網上看了很多資料,大多搞得很高大上。可能本人水平有限,實在是不會用。

那我就用最簡單爆力的辦法來做。

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

遞歸獲取數據,然后返回給視圖

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

定義一個視圖方法,然后遞歸調用。

@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)

打完收功!

轉載于:https://www.cnblogs.com/micenote/p/5032497.html

總結

以上是生活随笔為你收集整理的MVC 中 Razor 无限分类的展示的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。