0

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?

user2206329
  • 2,792
  • 10
  • 54
  • 81

2 Answers2

1

I use a foreach when looping through an ienumerable

foreach(var temp in Model.DefectDetails){
    @Html.TextBoxFor(x => temp.Description)
}

Hopefully this helps

Matt Bodily
  • 6,403
  • 4
  • 29
  • 48
  • In my experience every time you use a for helper (except displayfor) MVC is able to model bind. – Matt Bodily Oct 15 '13 at 13:47
  • Just read Jason Evans answer and googled it. This may help http://stackoverflow.com/questions/8894442/mvc-razor-view-nested-foreachs-model – Matt Bodily Oct 15 '13 at 13:50
0

You will have to use ToList()

var items = Model.DefectDetails.ToList();

    @for (int i = 0; i < items.Count; i++)
    {
        @Html.TextBoxFor(m => m.Description[i].ToBeAudited)
    }

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.

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
  • I guess that is not needed anymore `Count()` instead of `Count` property because you convert to a Generic list. – Snake Eyes Oct 14 '13 at 12:34
  • I have updated my code... this doesn't seem to work.. after the following @Html.TextBoxFor(m => m.Description[i] ... when I press dot nothing appears.. it says I cannot apply indexing to an ienumerable... Looks I might need to update the viewmodel.. just to say List instead of ienumerable... strange – user2206329 Oct 14 '13 at 12:45