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

I have a property in my model that is a type of collection (List). I would like to call for each element in this collection Html.DisplayFor or Html.EditorFor . How can i do this?

EDIT This is not a strong typed view. This is a template view. There is only ViewData.ModelMetadata.

+4
source share
3 answers

Can you try

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

Something like this in your opinion?

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

See also using Html.EditorFor with IEnumerable <T>

+2
source

The easiest way to do this is to simply add the "SelectedItem" property to your model:

 public class YourModel { public IEnumberable<Item> YourCollection { get; } public Item SelctedItem { get; set; } } 

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

 <% foreach (var item in Model.YourCollection) { %> Model.SelctedItem = item; <%= html.EditorFor(SelctedItem) %> ... <% } %> 
+1
source

Source: https://habr.com/ru/post/1306812/


All Articles