user137348
user137348

Reputation: 10332

ASP.NET MVC 2 : How to call DisplayFor for each item in a collection?

I have property in my model which is a collection type (List). I'd like to call for each item in this collection Html.DisplayFor or Html.EditorFor. How can I do this ?

EDIT It's not a strong-typed view. It's a templated view. There is only ViewData.ModelMetadata.

Upvotes: 4

Views: 6228

Answers (3)

Allen Wang
Allen Wang

Reputation: 998

Can you try

<% foreach (var item in Model.MyCollection) { %>
    <%= html.EditorFor(m=>item) %>
<% } %>

Upvotes: 8

Lee Smith
Lee Smith

Reputation: 6775

The easiest way to do this is just add a 'SelectedItem' property to your model:

public class YourModel
{

public IEnumberable<Item> YourCollection
{
get;
}


public Item SelctedItem
{
get;
set;
}


}

Then just assign each item in the list to the selctedItem property:

<% foreach (var item in Model.YourCollection) { %>   

Model.SelctedItem = item;

<%= html.EditorFor(SelctedItem) %>   
    ...   
<% } %> 

Upvotes: 0

Robert Harvey
Robert Harvey

Reputation: 180958

Something like this, in your view?

<% foreach (var item in Model.MyCollection) { %>
    <%= html.EditorFor... %>
    ...
<% } %>

See also using Html.EditorFor with an IEnumerable<T>

Upvotes: 2

Related Questions