Allow typing inside a Dropdownlist and run the search

Asked

Viewed 787 times

1

I have a DroDownList that lists Patients' names. I need to allow the user to type the patient’s "Name" directly into the Dropdownlist and when typing the Patient Name the system will perform the search.

HTML

<p><button type="button" id="btnNovoProduto" class="btn btn-primary btn-sm">NOVO PRODUTO</button></p>

<div class="modal fade" id="modalProduto" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
                <div class="modal-header bg-info">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h3>PRODUTO</h3>
                </div>
                <div class="modal-body">
                       <fieldset>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="col-md-8">
                                        <select id="ddlJquery" class="form-control input-sm">
                                            <option value="0">SELECIONE</option>
                                        </select>

                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-12">
                                    <div class="col-md-8">
                                        <input type="text" id="NomeDoPaciente" value="" class="form-group-sm" />
                                    </div>
                                </div>
                            </div>
                       </fieldset>

Javascript

@section Scripts {
    <script src="~/Scripts/select2.full.min.js"></script>    
    <script type="text/javascript">

        $(document).ready(function () {

            $('#btnNovoProduto').on('click', function () {
                ListarJQUERY();
                $("#modalProduto").modal({ backdrop: false });
            });

            function ListarJQUERY() {
                $.ajax({
                    url: "/Administrativo/Produto/BuscarAllProduto",
                    type: "post",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    processData: false,
                    data: null,
                    beforeSend: function () {
                        $("#divCarregando").show();
                    },
                    complete: function () {
                        $("#divCarregando").hide();
                    },
                    success: function (data) {
                        $('#ddlJquery').empty();
                        $('#ddlJquery').append('<option value="0">SELECIONE</option>');

                        $.each(data.lstSubTipo, function (i, subTipo) {
                            $('#ddlJquery').append('<option value=' + subTipo.TBPRODUTOID + '>' + subTipo.DSPRODUTO + '</option>');
                        });
                    },
                    error: function (result) {
                        alert(result.responseText);
                    }
                });

                $("#ddlJquery").select2({
                    allowClear: true,
                    ajax: {
                        type: 'GET',
                        url: '/Produto/BuscarParteProduto',
                        data: function (params) {
                            return {
                                id: 'e'//params.term
                            };
                        },
                        dataType: 'json',
                        processResults: function (data) {
                            return {
                                results: data
                            };
                        }
                    },
                    initSelection: function (element, callback) {
                        var id = $(element).val();
                        if (id) {
                            var url = '/Produto/BuscarParteProduto';
                            $.ajax(url + '/' + id, {
                                dataType: "json"
                            }).done(function (data) {
                                callback({ 'pNome': id, 'text': $('#NomeDoPaciente').val() })
                            });
                            console.log("passei");
                        } else {
                            callback({ 'pNome': $('#NomeDoPaciente').val(), 'text': $('#NomeDoPaciente').val() })
                        }
                    }
                });
            };


        });
    </script>
}

CONTROLER

public JsonResult BuscarParteProduto(string pNome)
        {
            try
            {
                List<TBProduto> lProdutoFiltrado = new List<TBProduto>();
                List<TBProduto> lTotalProduto = ObterListaProduto();
                if (!string.IsNullOrWhiteSpace(pNome))
                {

                    lProdutoFiltrado = lTotalProduto.Where(x => x.DSPRODUTO.ToUpper().Contains(pNome.ToUpper())).ToList<TBProduto>();
                }
                else
                {
                    lProdutoFiltrado = lTotalProduto.ToList();
                }
                return Json(lProdutoFiltrado.Select(x => new
            {
                id = x.TBPRODUTOID,
                text = String.IsNullOrWhiteSpace(x.DSPRODUTO) ? "" : x.DSPRODUTO,
            }), JsonRequestBehavior.AllowGet);
            }catch(Exception){
                throw;
            }
        }

public JsonResult BuscarAllProduto()
        {
            try
            {
                List<TBProduto> lTotalProduto = ObterListaProduto();
                List<TBProduto> lProdutoFiltrado = new List<TBProduto>();
                lProdutoFiltrado = lTotalProduto.ToList();
                return Json(new { lstSubTipo = lProdutoFiltrado.ToList() }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                throw;
            }
        }
  • This answer can help you solve your problem. http://answall.com/questions/59727/como-deixar-a-primeira-op%C3%A7%C3%A3o-disabled-e-selected/59747#59747

  • Good afternoon, friend, have you looked at Lect2? https://select2.github.io/

1 answer

1


Follow a statement from Select2. Don’t forget to create a new method in Patientecontroller called jsonLoadSelect2.

Statement:

    $("#ddlPacientes").select2({
        allowClear: true,
        ajax: {
            type: 'GET',
            url: '@Url.Action("jsonLoadSelect2", "Paciente")',
            data: function (params) {
                return {
                    id: params.term
                };
            },
            dataType: 'json',
            processResults: function (data) {
                return {
                    results: data
                };
            }
        },
        initSelection: function (element, callback) {
            var id = $(element).val();
            if (id) {
                var url = '@Url.Action("jsonLoadSelect2", "Paciente")';
                $.ajax(url + '/' + id, {
                    dataType: "json"
                }).done(function (data) {
                    callback({ 'id': id, 'text': $('#NomeDoPaciente').val() })
                });
                console.log("passei");
            } else {
                callback({ 'id': $('#NomeDoPaciente').val(), 'text': $('#NomeDoPaciente').val() })
            }
        }
    });

jsonLoadSelect2 method in the Patientcontroller:

public JsonResult jsonLoadSelect2(String id)
{
        IList<Paciente> pacientes;

        if (!String.IsNullOrWhiteSpace(id))
        {
            id = id.ToUpper();
            certificados = _paciente.GetByFilter(c => c.NomeDoPaciente.ToUpper().Contains(id.ToUpper()));
        }
        else
        {
            pacientes = _paciente.FindAll();
        }

        return Json(pacientes.Select(x => new
        {
            id = x.ID,
            text = String.IsNullOrWhiteSpace(x.NomeDoPaciente) ? "" : x.NomeDoPaciente,
        }), JsonRequestBehavior.AllowGet);

}

Should help in its implementation.

  • Good suggestion, I downloaded Select2-4.0.1.zip and unzipped the file, however I don’t know which file I should copy to my Solution, or should be copied the entire folder ?

  • <src="~/Scripts/Select2/js/Select2.full.js"></script> <link href="~/Scripts/Select2/css/Select2.css" rel="stylesheet" />

  • Andre is unable to implement the code, I edited the question and added the html code and the controler. In javascript there is a function to load the Select (I don’t know if it is necessary) that is mounted from a Boot called New Product and then the code you posted as an example.

  • Select2 does not need a charge button. When you click it, it loads the dropdown and already allows you to go typing the values.

  • Perfect Andre implemented the object, but I can’t get the value of Combobox, I created a new post to better explain the other situation, if you can help me [link]http://answall.com/questions/108999/pega-o-item-selectdo-plugin-select2-e-fazer-um-submit[link]

Browser other questions tagged

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