In short, use a for loop instead of a foreach loop (see answer here). You need to manually index it
MVC Razor displays a nested foreach model
EDIT: added sample code
@for(int i=0; i < Model.ListTwo.Count; i++) { @Html.HiddenFor(t => t.ListTwo[i].Id) }
Ok, for collections that inherit from ICollection, try
@for (int i = 0; i < Model.CollectionThree.Count; i++) { @Html.Hidden("CollectionThree[" + i + "].Id", Model.CollectionThree.ElementAt(i).Id) }
Other editing: To avoid using the property name, you can do something like
@for (int i = 0; i < Model.CollectionThree.Count; i++) { @Html.Hidden(Html.NameFor(t => Model.CollectionThree) + "[" + i + "]." + Html.NameFor(t =>Model.CollectionThree.ElementAt(i).Id) ,Model.CollectionThree.ElementAt(i).Id ) }
Its inelegant, but it does not encode the name of the property.
And then take these guys out of the loop
@{ var collectionname = Html.NameFor(t => Model.CollectionThree); var propname = Html.NameFor(t => Model.CollectionThree.First().Id); } @for (int i = 0; i < Model.CollectionThree.Count; i++) { @Html.Hidden( collectionname+ "[" + i + "]." + propname ,Model.CollectionThree.ElementAt(i).Id ) }
My apologies for non-compliance earlier. I logged out because I had other things to do. You can also do a null check, i.e., if count> 0, then assign propname, otherwise skip it all
source share