问题
I've got a form that contains a variable length list of textboxes, rendered using a template similar to this..
@Html.TextBox("items[" + itemIndex + "].Title", someValue)
So the final rendered HTML looks something like this...
<input id="items_0__Amount" type="text" value="Apple" name="items[0].Title">
<input id="items_1__Amount" type="text" value="Banana" name="items[1].Title">
<input id="items_2__Amount" type="text" value="Orange" name="items[2].Title">
On form submission this binds to my model just fine. However, I have a delete button that uses Javascript to remove one or more rows from the form. The problem is that, if you delete say the middle row, the HTML looks like this...
<input id="items_0__Amount" type="text" value="Apple" name="items[0].Title">
<input id="items_2__Amount" type="text" value="Orange" name="items[2].Title">
...and the indexes are no longer contiguous. This seems to confuse MVC and my model binder only gets passed the first row, not the last. Have I done something wrong, or does MVC just fail if indexes in lists aren't contiguous? What is the best solution to this problem?
I want to avoid using JS to re-index everything if possible.
Thanks!
回答1:
Phil Haack blogged about something similar to this a while ago, although I'm not sure if it is still relevant to MVC 3. The post includes a work-around for the non-sequential index problem -
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
来源:https://stackoverflow.com/questions/7399454/mvc-razor-model-binding-collections-when-an-element-is-missing