I have the following IEnumerable
public class AuditDetailsViewModel
{
public string CustAddress { get; set; }
public IEnumerable<DefectDetailsViewModel> DefectDetails { get; set; }
}
public class DefectDetailsViewModel
{
public string Description { get; set; }
public string Comments { get; set; }
}
In my razor view how I can enumerate over this using the Html helpers? If it was a list I could do the something like the following
@model AIS.Web.Areas.Inspector.ViewModel.AuditDetailsViewModel
@for (int i = 0; i < Model.DefectDetails.Count(); i++)
{
@Html.TextBoxFor(m => m.DefectDetails[i].Description)
}
but how can I do that if the viewmodel is an IEnumerable?
You will have to use
ToList()
EDIT:
You cannot apply indexing to an IEnumerable, that is true, which is why you must transform it into a List by using ToList().
If you use a for..each loop, then when you postback to the controller, the content in the textboxes will not be transferred. You must use a for...loop with an indexer, else the MVC model binder cannot bind the data correctly.
In your code, you're not calling ToList() before iterating over the collection, hence your getting the error that it cannot apply indexing to an enumerable.
I use a foreach when looping through an ienumerable
Hopefully this helps