Take the fields from a Select and pass to viewmodel

1

I have two Selects Multiple where their function is to change values as in the image below:

ThefirstoneintherealisaDropDownListwherehelooksforthebankinformation,followshiscode:

@Html.DropDownList("Avaible", ViewBag.Account as SelectList, new { multiple = "multiple", id = "Avaliable", name = "Avaliable" })

The other is a Select that receives these values, it follows your code:

 <select style="width:70px" id="Included" name="Included" multiple></select>

The two buttons transition the data from one to the other via JavaScript:

function Incluir() {
    $("#Included").append($("#Avaliable option:selected"));
}

And then it populates the select that gets the values, the problem is, I need to get those values and store them in a ViewModel variable called Accounts

  public List<int> Accounts { get; set; }

I have tried to do a JavaScript method that returns all values of Select, but I can not store this in the Accounts variable, this is the function I did:

function displayResult() {
    var x = document.getElementById("Included");
    var array = [];
    var i;
    for (i = 0; i < x.length; i++) {
        array[i] = x.options[i].value;
    }
    alert(array);
    $('#Accounts').push(array);
}

But he can not popular Accounts, could anyone help me how popular this List Accounts with the Select values? If you have a better method or help to transfer the Array to the Accounts. Ah forgot to speak, in the View has a field referencing the Accounts:

@Html.HiddenFor(m => Model.Accounts)
    
asked by anonymous 13.07.2018 / 15:30

1 answer

0

You do not need to store the selection in an input hidden "Accounts" this can even be done but you will need to change your model and add new treatments in the backend to process the input

As suggested in the comments, one solution is to rename your second select with name="Accounts[]" and ensure that all your items are selected before submitting to your controller.

function Incluir() {
  $("#Accounts").append($("#Avaliable option:selected"));
}

function displayResult() {
  //Essa linha de código vai selecionar todos os itens que existem
  //no select #Accounts para garantir a sua persistência à Controller
  $("#Accounts option").prop('selected', true);


  console.log($("#Accounts").val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><selectstyle="width:70px" id="Avaliable" name="Avaliable" multiple>
  <option value="123">123</option>
  <option value="321">321</option>
  <option value="111">111</option>
  <option value="222">222</option>
  <option value="333">333</option>
</select>
<button id="Adicionar" onclick="Incluir()">></button>
<select style="width:70px" id="Accounts" name="Accounts[]" multiple></select>
<br>
<button onclick="displayResult()">Enviar</button>
    
13.07.2018 / 22:00