如何在 C# 中将两个数组作为彼此的键和值

本文关键字:数组 两个 键和值 | 更新日期: 2023-09-27 18:33:20

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

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

<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--;
    })
});

如何在 C# 中将两个数组作为彼此的键和值

为了回发到模型,控件的 name 属性必须与属性的名称名称匹配,对于集合,name 属性必须具有索引器。由于<input type="text" name="contact_name[]" />包含非法名称,因此其值无法绑定到模型。

创建具有要编辑的属性的视图模型

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

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

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

在视图中

@model List<ContactVM>
@using(Html.BeginForm())
{
  <div id="contactlist">
    for(int i = 0; i < Model.Count; i++)
    {
      <div class="contact">
        @Html.TextBoxFor(m => m[i].Name)
        @Html.TextBoxFor(m => m[i].Phone)
        // Add index property to allow dynamic addition and deletion of contacts
        <input type="hidden" name="Index" value="@i" />
        <button type="button" class="deletecontact">Delete</button>
      </div>
    }
  </div>
  <button type="button" id="addcontact">Add More Focal Points</button>
  // Add html for a new contact
  <div id="newcontact"> // style this as hidden
    <div class="contact">
      <input type="text" name="[#].Name value />
      <input type="text" name="[#].Phone value />
      <input type="hidden" name="Index" value ="%"/>
      <button type="button" class="deletecontact">Delete</button>
    </div>
  </div>
  <input type="submit" value="Save" />
}

脚本

$('#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<ContactVM> model)
{
  //model now contains all the contacts with the name and phone
}

假设:

public class contactVM
{
    public contactVM()
    {
      contacts = new List<individualContactVM>()
    }
    public List<individualContactVM> 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 = "" }))
{    
<input type="text" name=contacts[0].Name/>
<input type="text" name=contacts[0].Phone/>

<input type="text" name=contacts[1].Name/>
<input type="text" name=contacts[1].Phone/>
<input type="text" name=contacts[2].Name/>
<input type="text" name=contacts[2].Phone/>
<input type="submit" value="Save"  />
}

等等。你必须有一组从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来做这样的事情。假设他们删除了第一个联系人,那么其余联系人需要将其索引减去 1。