How does MVC 4 List Model Binding work?

Eric picture Eric · Feb 12, 2013 · Viewed 79.7k times · Source

If I want a set of inputs in a form to bind to a List in MVC 4, I know that the following naming convention for input name attributes will work:

<input name="[0].Id" type="text" />
<input name="[1].Id" type="text" />
<input name="[2].Id" type="text" />

But I am curious about how forgiving the model binder is. For example, what about the following:

<input name="[0].Id" type="text" />
<input name="[3].Id" type="text" />
<input name="[8].Id" type="text" />

How would the model binder handle this? Would it bind to a List of length 9 with nulls? Or would it still bind to a List of length 3? Or would it choke altogether?

Why I care

I want to implement a dynamic form in which the user may add rows to the form, and also may delete rows from the form. So if I a user deletes row 2 out of 8 total rows, I want to know if I'll need to renumber all of the subsequent inputs.

Answer

Erik Funkenbusch picture Erik Funkenbusch · Feb 12, 2013

There is a specific wire format for use with collections. This is discussed on Scott Hanselman's blog here:

http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

Another blog entry from Phil Haack talks about this here:

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

Finally, a blog entry that does exactly what you want here:

http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/