MVC/Razor model binding collections when an element is missing

谁都会走 提交于 2019-12-21 12:17:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!