Pick up the selected item from the Select2 plugin and do a Submit

0

How to get the selected item from the DropDownList Select2 plugin ( link ), and send it to a Controller through a button submit?

SCREEN

CONTROLER

publicActionResultIndex(ContratoViewModelcontratoViewModel){intid=contratoViewModel.Id;}

SUBMITBUTTON

<inputclass="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>
    
asked by anonymous 19.01.2016 / 01:00

1 answer

1

Adriano, take a look at my answer on: link

Notice the javascript callback . When returning the values, it must fill hidden field with the customer code. In the MVC, the hidden field will be linked to the Model. You need to put the callback in your code to populate the hidden field and consequently your 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 fetch button, Model will already contain your client code and your controller method will receive the required information.

ContractController:

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

ClientController:

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);
}
    
19.01.2016 / 12:54