【问题标题】:Iterate for each item in IEnumerable迭代 IEnumerable 中的每个项目
【发布时间】:2016-10-11 14:14:28
【问题描述】:

我想我在这里遗漏了一些简单的东西。

在我的控制器中

public ActionResult ListPage()
    {
        return View(db.Sections.OrderBy(x=>x.Order).ToList());
    }

在我的 ListPage.cshtml 上

@model IEnumerable<Section>
@foreach (var item in Model)
{
    @Html.DisplayFor(item => item, "SectionTemplate")
}

在 Views/Shared/DisplayTemplates/SectionTemplate.cshtml 中我不知道该放什么。理想情况下,这个视图看起来像

@model Section
<h1>@Model.Title</h1>

但显然更健壮一些。 当我这样做时,我得到一个错误:

传入字典的模型项的类型为“System.Collections.Generic.List`1[Section]”,但此字典需要“Section”类型的模型项。

如何更改此代码以访问模板中单个模型的属性?

谢谢!

【问题讨论】:

  • ListPage 视图中没有 DisplayFor 是否可以工作?
  • ListPage 视图是否显示?是的。

标签: c# asp.net .net asp.net-mvc asp.net-mvc-4


【解决方案1】:

在您的代码中,在 lambda 内部,item 解析为所述 lambda 的参数,而不是在外部范围中声明的 item。只需重命名 lambda 的参数,它应该可以按预期工作:

@foreach (var item in Model)
{
    @Html.DisplayFor(_ => item, "SectionTemplate")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-25
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多