【问题标题】:How to put two arrays as key and values of each other in C#?如何在 C# 中将两个数组作为彼此的键和值?
【发布时间】: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 的一些基础知识的误解。为了将 &lt;input type="text" name="contact_name[]" /&gt; 的值绑定到属性,该属性需要命名为 contact_name[],这是非法的。
  • 比我怎么添加很多联系人
  • 当我点击时,我的文本框旁边有一个按钮,它将创建相同的两个文本框
  • 是的,你可以有&lt;input name="contact["ABC"].Name" ../&gt;&lt;input name="contact["ABC"].Phone" ../&gt;,但在这种情况下你需要添加另一个隐藏输入&lt;input name="contact.Index" value="ABC" ../&gt;,以便DefaultModelBinder匹配正确的项目
  • @IsaacBolinger,通常您会在 for 循环中呈现现有项目并添加 &lt;input name="Index" value="@i" /&gt;,但对于动态添加的项目(通过 javascript),Index 值可能是 (new Date()).getTime()。由于Index 属性,您可以添加或删除项目,并且集合仍将在回发时正确绑定(无需重新编号),并且集合在视图中呈现时对其进行排序。

标签: c# asp.net-mvc-5


【解决方案1】:

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

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

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
}

【讨论】:

    【解决方案2】:

    假设:

    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 来做这样的事情。假设如果他们删除了第一个联系人,那么其余的联系人需要将他们的索引减一。

    【讨论】:

    • 艾萨克。仅供参考,我添加了一个答案,显示了一种使用 Index 属性动态添加和删除集合项的技术,这样您就不需要重新编号索引器。
    • 这很酷。我想我在某个地方读到了一个糟糕的教程,上面说“必须”这样做。我有一个非常复杂的表格,我开始了,谢天谢地没有完成。重新编号的文件很大。
    猜你喜欢
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 2012-01-19
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多