ASP.NET MVC - issues with binding a non-sequential list with the default model binder
- Mar 2, 2013
For the ASP.NET MVC default model binder to bind a list successfully, the list must be sequential with unbroken indices.
For the following examples, the server side model will be
public class ItemsModel
{
public IList<string> Items { get; set; }
}
Non-sequential form submits when using indexes which don’t start from zero i.e. Item[2], Item[3], etc will result in incomplete form data being loaded by the model binder.
The following will not bind, and will result in the model being NULL:
<input type="text" name="Item[1].Name" value="Item1" />
<input type="text" name="Item[3].Name" value="Item2" />
<input type="text" name="Item[4].Name" value="Item3" />
The following will only partially bind, and will result in the model containing items 0, 1, 2:
<input type="text" name="Item[0].Name" value="Item0" />
<input type="text" name="Item[1].Name" value="Item1" />
<input type="text" name="Item[2].Name" value="Item2" />
<input type="text" name="Item[4].Name" value="Item3" />
whereas
<input type="text" name="Item[0].Name" value="Item0" />
<input type="text" name="Item[1].Name" value="Item1" />
<input type="text" name="Item[2].Name" value="Item2" />
<input type="text" name="Item[3].Name" value="Item3" />
will bind since the list is sequential.