如何在C#中将两个数组作为键和值互相放置?

我在ASP.Net MVC中有一个表单,其中联系人可以是一个或多个

例如:一个项目可以有一个或多个联系人。 我创建了我的表单,它有一个带有两个文本框的div,比如打击:

Name: Phone

当我发布表单时,如何将联系人姓名和电话数组作为单个数组的键和值。

动态生成文本框的脚本:

  $(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('
Name: Phone Remove
'); //add input box } }); $(wrapper).on("click", ".remove_field", function (e) { //user click on remove text e.preventDefault(); $(this).parent('div').remove(); x--; }) });

为了回发到模型,控件的name属性必须与属性的name属性匹配,对于集合, name属性必须具有索引器。 由于包含非法名称,因此其值不能绑定到您的模型。

使用要编辑的属性创建视图模型

 public class ContactVM { public string Name { get; set; } public string Phone { get; set; } } 

在控制器中,初始化要显示的任何现有联系人的集合

 public ActionResult Edit() { List model = new List(); // add any existing contacts to edit return View(model); } 

在视图中

 @model List @using(Html.BeginForm()) { 
for(int i = 0; i < Model.Count; i++) {
@Html.TextBoxFor(m => m[i].Name) @Html.TextBoxFor(m => m[i].Phone) // Add index property to allow dynamic addition and deletion of contacts
}
// Add html for a new contact
// style this as hidden
}

脚本

 $('#addcontact).click(function() { var count = $('#contactlist').find('.contact').length; if (count < 10) { var index = (new Date()).getTime(); // unique indexer var clone = $('#newcontact').clone(); clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']')); clone.find('input[type="hidden"]').val(index); $('#contactlist').append(clone.html()); } else { // cant add any more } }); $('.deletecontact').click(function() { $(this).closest('.contact').remove(); } 

发布方法

 public ActionResult Edit(List model) { //model now contains all the contacts with the name and phone } 

假设:

 public class contactVM { public contactVM() { contacts = new List() } public List contacts {get;set;} } public class individualContactVM { public string Name {get;set;} public string Phone {get;set;} } 

然后你会有这组输入框:例如3个联系人:

 @model Benafsh.Website.contactVM @using (Html.BeginForm("SaveContact", "Contact", FormMethod.Post, new { name = "thisform", novalidate = "" })) {        } 

等等。 您必须有一组从0到N的连续数字,否则它将无法正常工作。

你的控制器只是:

 [Authorize] public class ContactController : Controller { [HttpPost] public void SaveContact(contactVM input) { //write code here to take the info out of contactVM and put it wherever } } 

实际上,您遇到的一个麻烦就是当您的用户希望删除其中一个时。 然后,您必须重新编号其后的项目的索引。 你将不得不写一些javascript来做这样的事情。 假如他们删除了第一个联系人,那么其余的联系人需要将他们的索引减一。