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.

1

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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. :)
What will happen if I want to insert more items than Model.Count ? -hutchonoid

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.