MVC /剃刀模型绑定集合的元素缺失时, [英] MVC/Razor model binding collections when an element is missing
问题描述
我有一个包含文本框的长度可变的列表形式,用类似下面的模板呈现。
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)
所以最后呈现的HTML看起来像这样...
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">
在表单提交这个绑定到我的模型就好了。不过,我有一个删除按钮使用JavaScript来从表格中删除一个或多个行。问题是,如果你说的删除排中间的HTML看起来像这样...
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">
...和索引不再是连续的。这似乎混淆MVC和我的模型只粘结剂被传递的第一行,而不是最后。难道我做错了什么事,或者如果在列表中的索引不是连续的不只是MVC失败?解决这个问题最好的解决办法是什么?
...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?
我要避免使用JS重新索引一切,如果可能的。
I want to avoid using JS to re-index everything if possible.
谢谢!
推荐答案
菲尔哈克博客上讲述一些类似的前一阵子,虽然我不知道,如果它仍然是相关的MVC 3,岗位包括一次工作周围的非顺序索引的问题 -
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/存档/ 2008/10/23 /模型绑定到一个-list.aspx
这篇关于MVC /剃刀模型绑定集合的元素缺失时,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!