Grab the selected item from the Select2 plugin and make a Submit

Asked

Viewed 931 times

0

How to get the selected item from the Dropdownlist plugin Select2 (https://plugins.jquery.com/select2/), and send to a Controler via an Submit button ?

CANVAS inserir a descrição da imagem aqui

CONTROLER

public ActionResult Index(ContratoViewModel contratoViewModel)
{
int id = contratoViewModel.Id;
}

BUTTON THAT SUBMITS

 <input class="btn btn-primary" value="Buscar" type="submit" id="btnBuscar" />

HTML

    @using(Html.BeginForm("Index", "Contrato", FormMethod.Get))
    {
        <div class="row">
            <div class="col-xs-3">
                <label>Cliente</label><br />
                <select id="ClienteID" name="ClienteID" class="form-control">
                    <option value="0">[SELECIONE]</option>
                </select>
            </div>
<div class="col-xs-3">
            @Html.LabelFor(x => x.ContratoViewModel.NumeroContrato)
            @Html.TextBoxFor(x => x.ContratoViewModel.NumeroContrato, new { @class = "form-control" })
        </div>

        <div class="col-xs-3">
            @Html.LabelFor(x => x.ContratoViewModel.Responsavel)
            @Html.TextBoxFor(x => x.ContratoViewModel.Responsavel, new { @class = "form-control" })
        </div>

        <div class="col-xs-2">
            @Html.LabelFor(x => x.ContratoViewModel.Status)<br />
            @Html.RadioButtonFor(x => x.ContratoViewModel.Status, "true", new { @checked = "checked" }) Ativo
            &nbsp;&nbsp;&nbsp;
            @Html.RadioButtonFor(x => x.ContratoViewModel.Status, "false") Inativo
        </div>
}

JAVASCRIPT

<script src="~/Content/Scripts/select2.full.min.js"></script>

<script type="text/javascript">

    $(document).ready(function () {

        $("#ClienteID").select2({
            allowClear: true,
            ajax: {
                type: 'GET',
                url: '/Contrato/ListarClienteJSON',
                data: function (params) {
                    return {
                        pNome: params.term
                    };
                },
                dataType: 'json',
                processResults: function (data) {
                    return {
                        results: data
                    };
                }
            }
        });

    });
</script>

1 answer

1


Adriano, take a look at my answer on: /a/108564/21263

Note the javascript callback. When returning the values, it must fill in Hidden field with the client code. In the MVC, Hidden field will be linked to the Model. You need to put the callback in your code to fill the Hidden field and, consequently, its model.

<input type="hidden" id="CodigoDoCliente" 
                     name="CodigoDoCliente" 
                     value="@Model.CodigoDoCliente" />

The callback:

initSelection: function (element, callback) {
            var id = $(element).val();
            if (id) {
                var url = '@Url.Action("ListarClienteJSON", "Cliente")';
                $.ajax(url + '/' + id, {
                    dataType: "json"
                }).done(function (data) {
                    callback({ 'id': id, 'text': $('#Nome').val() })
                });
            } else {
                callback({ 'id': $('#IdDoCliente').val(), 'text': $('#Nome').val() })
            }
        }

When you click the search button, the Model will already contain your client’s code and your controller’s method will receive the necessary information.

Contratocontroller:

public ActionResult Index(ContratoViewModel contratoViewModel)
{
   return View();
}

Clientecontroller:

public JsonResult ListarClienteJSON(Int32? idCliente)
{
  List<Cliente> clientes;

  if (idCliente.HasValue)
  {
    clientes = _clientesBSS.obterCliente(c => c.ID == idCliente.Value);
  }
  else 
  {    
    clientes = _clientesBSS.obterClientes().ToList();
  }

  return Json(clientes.Select(c => new
  {
     Id = c.ID,
     Nome = String.IsNullOrWhiteSpace(c.Nome) ? "" : c.Nome
  }), JsonRequestBehavior.AllowGet);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.