0

Normally, if we want to bind a list to our viewmodel we would need to do something like:

public class ViewModel
{
    public List<SomeModel> MyList { get; set; }
}

@for (int i = 0; i < Model.MyList.Count; i++)
{
    <input asp-for="MyList[i].SomeProp" ..>
}

Which gives elements with names like MyList[0].SomeProp or MyList_0__SomeProp.

But what if my list is empty at first and I want to fill it client-side (user can add as many elements as he wants).

Is it necessary that I maintain an index (that MUST start at 0) and whenever the user adds an element I name it like that? Thing is, if the user deletes an element then I have to re-order the indexs right?

Is there a way to bind to a list in our viewmodel without having to use indexing, some like MyList[].SomeProp directly (even though I don't think the server would know how to split elements in this case).

Thank you.

Haytam
  • 4,643
  • 2
  • 20
  • 43
  • Refer [this answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) for some options –  Oct 28 '18 at 10:03
  • For the pure js option, refer also [This answer](https://stackoverflow.com/questions/24026374/adding-another-pet-to-a-model-form/24027152#24027152) You cannot omit the indexers, but adding the hidden input for the collection indexer means that they do not have to be zero based or consecutive –  Oct 28 '18 at 10:31
  • Do we have to have inpuits named `List.Index` or `List[index].Index` with `value="index"`? – Haytam Oct 28 '18 at 12:43
  • In your case i will be `name="MyList.Index"`, and the `value` must match the collection indexer - e.g. if you have an input with `name="MyList[abc].SomeProp"`, then it would be `` –  Oct 28 '18 at 20:39

0 Answers0