I have a ViewModel which contains a List.
The examples I've seen show:
Accessing the List items by iterating over all of them:
for (var i = 0; i < Model.Compliances.Count; i++)
{
<%=Html.HiddenFor(x => x.Compliances[i].ComplianceId) %>
<%=Html.TextBoxFor(x => x.Compliances[i].ComplianceName) %>
}
OR Specifying a hard coded position in the List:
<%=Html.HiddenFor(x => x.Compliances[2].ComplianceId) %>
<%=Html.TextBoxFor(x => x.Compliances[2].ComplianceName) %>
I am wondering if there is some way to bind a particular List item to a control by something more concrete like its id, instead of what position it happens to have in the List?
Thanks for any help on this!
You are stuck in WebForms terminology.
These are called Html Helpers, not controls. These helpers render HTML and do not "bind" anything in the sense you are thinking of. They're called helpers because they simply help to format the data in the correct way.
The reason that the helpers use specific indexes as you see is because the when the forms are posted back to the server, they must be indexed on a 0 based form so the model binder can discover them and recreate the model. It does this by two things, name and index, not by id's of values or anything else.
So if you want a list to be bound on postback, then it must be a 0 based index... OR it must use an "Index" value, as defined in the "non-sequential indexes" section of this article:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/