【发布时间】:2014-12-07 06:54:41
【问题描述】:
我在 ASP.Net MVC 中有一个表单 其中联系人可以是一个或多个
例如:一个项目可以有一个或多个联系人。 我创建了我的表单,它有一个带有两个文本框的 div:
<div class="form-group">
<label class="control-label col-md-2">Focal Points</label>
<div class="col-md-10">
<div class="input_fields_wrap">
<button class="add_field_button btn">Add More Focal Points</button>
<div style="margin:4px;">
Name: <input type="text" name="contact_name[]" />
Phone <input type="text" name="contact_phone[]" />
</div>
</div>
</div>
</div>
当我发布表单时,如何将联系人姓名和电话数组作为单个键和值数组获取。
动态生成文本框的脚本:
<script>
$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div style="margin:4px;">Name: <input type="text" name="contact_name[]"/> Phone <input type="text" name="contact_phone[]" /><a href="#" class="remove_field">Remove</a></div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
【问题讨论】:
-
您对 Http 和 MVC 的一些基础知识的误解。为了将
<input type="text" name="contact_name[]" />的值绑定到属性,该属性需要命名为contact_name[],这是非法的。 -
比我怎么添加很多联系人
-
当我点击时,我的文本框旁边有一个按钮,它将创建相同的两个文本框
-
是的,你可以有
<input name="contact["ABC"].Name" ../>,<input name="contact["ABC"].Phone" ../>,但在这种情况下你需要添加另一个隐藏输入<input name="contact.Index" value="ABC" ../>,以便DefaultModelBinder匹配正确的项目 -
@IsaacBolinger,通常您会在
for循环中呈现现有项目并添加<input name="Index" value="@i" />,但对于动态添加的项目(通过 javascript),Index值可能是(new Date()).getTime()。由于Index属性,您可以添加或删除项目,并且集合仍将在回发时正确绑定(无需重新编号),并且集合在视图中呈现时对其进行排序。
标签: c# asp.net-mvc-5