1 回答

TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊
你的問題是部分呈現(xiàn)基于單個(gè)AdminProductDetailModel
對(duì)象的html ,但你試圖回發(fā)一個(gè)集合。當(dāng)您動(dòng)態(tài)地添加一個(gè)新的對(duì)象,你繼續(xù)增加,看起來像重復(fù)控制<input name="productTotalQuantity" ..>
(這也創(chuàng)造因?yàn)橹貜?fù)的無效的HTML id
屬性),其中作為他們需要<input name="[0].productTotalQuantity" ..>
,<input name="[1].productTotalQuantity" ..>
等等,以綁定到一個(gè)集合上回發(fā)。
的DefaultModelBinder
要求,對(duì)于藏品的索引從零開始,并是連續(xù)的,或者表單值包括Index=someValue
其中P是someValue
(例如<input name="[ABC].productTotalQuantity" ..><input name="Index" value="ABC">
,這在菲爾哈克的文章中詳細(xì)解釋模型綁定到一個(gè)列表。使用索引方法通常更好,因?yàn)樗€允許您從列表中刪除項(xiàng)目(否則,有必要重命名所有現(xiàn)有控件,以便索引器是連續(xù)的)。
兩種可能的解決方法。
選項(xiàng)1
對(duì)部分視圖使用BeginItemCollection幫助器。此幫助程序?qū)?code>Index基于GUID 呈現(xiàn)值的隱藏輸入。您需要在局部視圖和渲染現(xiàn)有項(xiàng)目的循環(huán)中使用它。你的部分看起來像
@model IKLE.Model.ProductModel.AdminProductDetailModel@using(Html.BeginCollectionItem()) { <div class="editor-field"> @Html.LabelFor(model => model.fkConfigChoiceCategorySizeId) @Html.DropDownListFor(model => model.fkConfigChoiceCategorySizeId, Model.sizeList, "--Select Size--") @Html.ValidationMessageFor(model => model.fkConfigChoiceCategorySizeId) </div> ....}
選項(xiàng)2
手動(dòng)創(chuàng)建表示具有“假”索引器的新對(duì)象的html元素,將它們放在隱藏容器中,然后在“添加”按鈕事件中,克隆html,更新索引器和索引值,并將克隆元素附加到DOM。要確保html正確,請(qǐng)?jiān)?code>for循環(huán)中創(chuàng)建一個(gè)默認(rèn)對(duì)象并檢查它生成的html。此答案中顯示了此方法的一個(gè)示例
<div id="newItem" style="display:none"> <div class="editor-field"> <label for="_#__productTotalQuantity">Quantity</label> <input type="text" id="_#__productTotalQuantity" name="[#].productTotalQuantity" value /> .... </div> // more properties of your model</div>
注意使用'假'索引器來防止這個(gè)被綁定在帖子后面('#'和'%'不匹配,所以它們會(huì)被忽略DefaultModelBinder
)
$('#addField').click(function() { var index = (new Date()).getTime(); var clone = $('#NewItem').clone(); // Update the indexer and Index value of the clone clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']')); clone.html($(clone).html().replace(/"%"/g, '"' + index + '"')); $('#yourContainer').append(clone.html());}
選項(xiàng)1的優(yōu)點(diǎn)是您強(qiáng)烈鍵入模型的視圖,但這意味著每次添加新項(xiàng)目時(shí)都要調(diào)用服務(wù)器。選項(xiàng)2的優(yōu)點(diǎn)是它全部完成了客戶端,但如果你對(duì)模型進(jìn)行任何更改(例如向?qū)傩蕴砑域?yàn)證屬性),那么你還需要手動(dòng)更新html,使維護(hù)更加困難。
最后,如果您正在使用客戶端驗(yàn)證(jquery-validate-unobtrusive.js),那么每次向DOM添加新元素時(shí)都需要重新解析驗(yàn)證器,如本答案中所述。
$('form').data('validator', null);$.validator.unobtrusive.parse($('form'));
當(dāng)然,您需要更改POST方法以接受集合
[HttpPost]public ActionResult AddDetail(IEnumerable<AdminProductDetailModel> model){ ....}
- 1 回答
- 0 關(guān)注
- 621 瀏覽
添加回答
舉報(bào)