ASP.NET MVC Model Binding of an array of object with arbitary indices

Edit
For the default ASP.NET MVC Model Binding of an array of object, if the index numbers are not sequential then the values will not be bound correctly. Such situation can arise when you delete some records using say jQuery and AJAX calls, causing index sequence to break. In order to take care of this issue you need to supply an arbitrary index per employee record using a hidden form field. The following HTML markup shows how this is done:
...
<tr>
<td align="right" nowrap="nowrap" width="15%">
<input  type="hidden" name="employees.Index" value="100" />
<input name="employees[100].id" type="text" size="20" />
</td>
<td>
<input name="employees[100].FirstName" type="text" />
</td>
<td>
<input name="employees[100].LastName" type="text" />
</td>
</tr>
...

Notice the hidden form field employees.Index whose value is set to any arbitrary index (100 in this case). The text input fields then use employees[<index_value>] format for name attribute. In this case even if the indices are not sequential the default binder will map the data correctly with the help of the hidden index value.
ASP.NET MVC Model Binding of an array of object with arbitary indices ASP.NET MVC Model Binding of an array of object with arbitary indices Reviewed by DF on 9:03:00 PM Rating: 5
©DF. Powered by Blogger.