动态创建的文本框未绑定到模型 [英] Dynamically Created Textboxes Not Bound To Model
本文介绍了动态创建的文本框未绑定到模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的视图模型包含一个字符串列表:
My viewmodel contains a list of strings:
public class SupplierViewModel
{
public Supplier Supplier { get; set; }
public List<string> Numbers;
}
用户可以在视图中添加任意数量的字符串:
The user can add any number of strings in the view:
<div class="editor-label">
@Html.LabelFor(model => model.Numbers)
</div>
<div id="allNumbers">
@for (int i = 0; i < Model.Numbers.Count; i++)
{
<div class="editor-label">
@Html.TextBoxFor(m => m.Numbers[i])
</div>
}
</div>
<div id="newNumber" style="display:none;">
<input type="text" name="Numbers[#]" style="display:block;" />
</div>
<button type="button" id="addNumber" >Add</button>
这是通过jquery在客户端完成的:
This is done on the client side with jquery:
var container = $('#allNumbers');
$('#addNumber').click(function () {
var index = container.children().length;
var clone = $('#newNumber').clone();
clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
container.append(clone.html());
});
我的问题是,即使将所有动态添加的字符串都命名为"Numbers [i]",也不会将它们发送回控制器. 我在这里想念什么?
My problem is that none of the dynamically added strings are sent back to the controller even tough they are all named "Numbers[i]". What am I missing here?
推荐答案
Numbers
是一个字段,而DefaultModelBinder
无法设置字段的值.您需要通过添加getters/setters使其成为属性
Numbers
is a field and the DefaultModelBinder
cannot set the value of a field. You need to make it a property by adding getters/setters
public List<string> Numbers { get; set; }
这篇关于动态创建的文本框未绑定到模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文