迭代IEnumerable中的每一项
本文关键字:一项 IEnumerable 迭代 | 更新日期: 2023-09-27 18:12:27
我想我错过了一些简单的东西。
在我的控制器中有
public ActionResult ListPage()
{
return View(db.Sections.OrderBy(x=>x.Order).ToList());
}
在列表页上。我有
@model IEnumerable<Section>
@foreach (var item in Model)
{
@Html.DisplayFor(item => item, "SectionTemplate")
}
在Views/Shared/DisplayTemplates/SectionTemplate。我不知道该放什么。理想情况下,这个视图看起来像
@model Section
<h1>@Model.Title</h1>
但显然更健壮一些。当我这样做时,我得到一个错误:
传入字典的模型项的类型是System.Collections.Generic。列出' 1[Section]',但此字典需要'Section'类型的模型项。
我如何修改这段代码来访问模板中单个模型的属性?
谢谢!
在您的代码中,在lambda内部,item
解析到所述lambda的参数,而不是在外部作用域中声明的item
。只需重命名lambda的参数,它应该像预期的那样工作:
@foreach (var item in Model)
{
@Html.DisplayFor(_ => item, "SectionTemplate")
}