您的位置:首页 > 其它

MVC 中 Razor 无限分类的展示

2015-12-09 13:08 363 查看
在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

递归获取数据,然后返回给视图

abcContext db = newabcContext();
public ActionResult Index()
{
var categoryList = GetCategoryList(0);
return View(categoryList);
}

[NonAction]
public List<NewsCategoriesViewModel> GetCategoryList(int Id)
{
List<NewsCategoriesViewModel> uvModel = new List<NewsCategoriesViewModel>();

var perentList = db.Set<NewsCategory>().Where(p => p.ParentCategoryId == Id).ToList();

if (perentList.Count > 0)
{
foreach (var item in perentList)
{
NewsCategoriesViewModel userViewModel = new NewsCategoriesViewModel
{
Id = item.CategoryId,
Name = item.CategoryName,
children = new List<NewsCategoriesViewModel>()
};
List<NewsCategoriesViewModel> tempList = GetCategoryList(item.CategoryId);
if (tempList.Count > 0)
{
//这里出错了;
//userViewModel.children.Add(tempList);
userViewModel.children = tempList;
}
uvModel.Add(userViewModel);
}
}
return uvModel;
}
}


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)


打完收功!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: