How to put two arrays as key and values of each other in C#?

孤街浪徒 提交于 2019-12-08 06:28:15

问题


I have a form in ASP.Net MVC where contacts can be one or many

for example: a project can have one or many contact persons. I created my form it it has a div with two textboxes like 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>

when I post my form how can I get the array of contact names and phones as a single array of key and values.

script that generates textboxes dynamically:

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


回答1:


In order to post back to a model, the name attribute of the control must match the name name of the property, and for collections, the name attribute must have an indexer. Since <input type="text" name="contact_name[]" /> contains an illegal name, its value cannot be bound to your model.

Create a view model with the properties you want to edit

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

In your controller, initialize a collection of any existing Contacts you want to display

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

And in the view

@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" />
}

Script

$('#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();
}

Post method

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



回答2:


Assume:

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

then you would have this group of input boxes: for instance 3 contacts:

@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"  />
}

and so on. You have to have a contiguous set of numbers from 0 to N or it won't work right.

Your controller would simply be:

[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
    }
} 

Indeed, one of the troubles you will have is when your user wishes to delete one of them. Then you must renumber the indexes for the items following it. You will have to write some javascript to do such a thing. Say if they delete the first contact, then the rest of the contacts need their index subtracted by one.



来源:https://stackoverflow.com/questions/27340434/how-to-put-two-arrays-as-key-and-values-of-each-other-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!