asp.net-mvc-3modelbindersdefaultmodelbinder

MVC3 Non-Sequential Indices and DefaultModelBinder


Is it true that the default model binder in MVC 3.0 is capable of handling non-sequential indices (for both simple and complex model types)? I've come across posts that suggest it should, however in my tests it appears that it does NOT.

Given post back values:

items[0].Id = 10
items[0].Name = "Some Item"
items[1].Id = 3
items[1].Name = "Some Item"
items[4].Id = 6
items[4].Name = "Some Item"

And a controller method:

public ActionResult(IList<MyItem> items) { ... }

The only values that are loaded are items 0 and 1; item 4 is simply ignored.

I've seen numerous solutions to generate custom indices (Model Binding to a List), however they all appear to targeting previous versions of MVC, and most are a bit 'heavy-handed' IMO.

Am I missing something?


Solution

  • I have this working, you have to remember to add a common indexing hidden input as explained in your referenced article:

    The hidden input with name = Items.Index is the key part

    <input type="hidden" name="Items.Index" value="0" />
    <input type="text" name="Items[0].Name" value="someValue1" />
    
    <input type="hidden" name="Items.Index" value="1" />
    <input type="text" name="Items[1].Name" value="someValue2" />
    
    <input type="hidden" name="Items.Index" value="3" />
    <input type="text" name="Items[3].Name" value="someValue3" />
    
    <input type="hidden" name="Items.Index" value="4" />
    <input type="text" name="Items[4].Name" value="someValue4" />
    

    hope this helps