bboyk bboyk - 1 month ago 12
ASP.NET (C#) Question

Iterate for each item in IEnumerable

I think I am missing something simple here.

In my controller I have

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


On the ListPage.cshtml I have

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


And in the Views/Shared/DisplayTemplates/SectionTemplate.cshtml I'm not sure what to put. Ideally this view would look like

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


But a little more robust obviously.
When I do that, I get an error:


The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Section]', but this dictionary requires a model item of type 'Section'.


How can I change this code to access the properties on the individual model in the template?

Thanks!

Answer

In your code, inside of the lambda, item resolves to the parameter of said lambda, and not the item declared in the outer scope. Just rename the parameter of your lambda and it should work as expected:

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