4

I'm trying to add multiple items of the same type at once in a single View, while giving the model.

@model List<Item>

For the view, It renders, when I post back, the model is null, even though the form data is sent correctly but for some reason the mapping is not happening.

hutchonoid
  • 32,982
  • 15
  • 99
  • 104
Rami Sakr
  • 372
  • 1
  • 14
  • you need custom model binder - http://www.codeproject.com/Articles/605595/ASP-NET-MVC-Custom-Model-Binder – Typist Jan 06 '14 at 13:27

1 Answers1

2

For complex items you need to index your collections for the model binder.

Change your loop to this which will be picked up by the model binder (without seeing your view or model I am using Field for demo purposes here).

   @for (int i = 0; i < Model.Count; i++)
    {
        .....
        @Html.EditorFor(model => Model[i].Field)
        .....
    }

They will then be posted back to the server.

For more info on it see here:

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

hutchonoid
  • 32,982
  • 15
  • 99
  • 104
  • 1
    Thanks, I just need to also ask, What If I want at least one item in the collection to be filled without having the ModelState complain about the other required fields that weren't filled. – Rami Sakr Jan 06 '14 at 13:38
  • No probs, I've not had to do that before. You might have to add a flag to the model to say which item you want to remove the modelstate errors for. Then remove it on post. I would create another question as it is a good one to ask and someone else will have more info i'm sure. :) – hutchonoid Jan 06 '14 at 13:46
  • What will happen if I want to insert more items than Model.Count ? -hutchonoid – Bimal Das Aug 07 '16 at 13:00