views:

461

answers:

2

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.

+2  A: 

Something like this, in your view?

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

See also http://stackoverflow.com/questions/1478378/using-html-editorfor-with-an-ienumerablet

Robert Harvey
But How to do this in a temple view. There is no Model.items. Just ViewData.ModelMetadata..
If your collection is in a ViewData item, it would be something like `foreach(MyItemType item in (IEnumerable<MyItemType>)ViewData["MyCollection"])`
Robert Harvey
yes but the MyItemType could be anything.. therefor I'm trying to create template.. Something like here http://www.matthidinger.com/archive/2009/08/15/creating-a-html.displayformany-helper-for-mvc-2.aspx but I don't get the expression stuff :-(
Ah, you trapped me. I didn't know that's what you wanted. You can build stuff like this but it's not for the faint of heart. He's using functors and expression trees in his `DisplayForMany`. Even if you use his function, you will still be required to specify your type for the generic method.
Robert Harvey
A: 

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) %>   
    ...   
<% } %> 
Lee Smith