1 回答
TA貢獻2003條經驗 獲得超2個贊
你的問題是部分呈現基于單個AdminProductDetailModel對象的html ,但你試圖回發一個集合。當您動態地添加一個新的對象,你繼續增加,看起來像重復控制<input name="productTotalQuantity" ..>(這也創造因為重復的無效的HTML id屬性),其中作為他們需要<input name="[0].productTotalQuantity" ..>,<input name="[1].productTotalQuantity" ..>等等,以綁定到一個集合上回發。
的DefaultModelBinder要求,對于藏品的索引從零開始,并是連續的,或者表單值包括Index=someValue其中P是someValue(例如<input name="[ABC].productTotalQuantity" ..><input name="Index" value="ABC">,這在菲爾哈克的文章中詳細解釋模型綁定到一個列表。使用索引方法通常更好,因為它還允許您從列表中刪除項目(否則,有必要重命名所有現有控件,以便索引器是連續的)。
兩種可能的解決方法。
選項1
對部分視圖使用BeginItemCollection幫助器。此幫助程序將Index基于GUID 呈現值的隱藏輸入。您需要在局部視圖和渲染現有項目的循環中使用它。你的部分看起來像
@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>
....}選項2
手動創建表示具有“假”索引器的新對象的html元素,將它們放在隱藏容器中,然后在“添加”按鈕事件中,克隆html,更新索引器和索引值,并將克隆元素附加到DOM。要確保html正確,請在for循環中創建一個默認對象并檢查它生成的html。此答案中顯示了此方法的一個示例
<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>
注意使用'假'索引器來防止這個被綁定在帖子后面('#'和'%'不匹配,所以它們會被忽略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());}選項1的優點是您強烈鍵入模型的視圖,但這意味著每次添加新項目時都要調用服務器。選項2的優點是它全部完成了客戶端,但如果你對模型進行任何更改(例如向屬性添加驗證屬性),那么你還需要手動更新html,使維護更加困難。
最后,如果您正在使用客戶端驗證(jquery-validate-unobtrusive.js),那么每次向DOM添加新元素時都需要重新解析驗證器,如本答案中所述。
$('form').data('validator', null);$.validator.unobtrusive.parse($('form'));當然,您需要更改POST方法以接受集合
[HttpPost]public ActionResult AddDetail(IEnumerable<AdminProductDetailModel> model){
....}- 1 回答
- 0 關注
- 629 瀏覽
添加回答
舉報
