Clear List after Request via JS Dropdownlist in Cascade

Asked

Viewed 74 times

0

I have 2 Droplist one of Client and another of Project, after selecting the client he should receive the projects that are with Idcliente, I managed to do everything right, however when selecting another client, he adds in the Dropdownlist and does not delete those who have no relationship with the Client where I am missing?

[Controller]

       [HttpPost]
    public ActionResult obterProjeto(int idCliente)
    {
        List<Projeto> ListaExemplo = new List<Projeto>();

        var teste = _context.Projeto.Where(s => s.IdCliente == idCliente)
            .Select(ss => new
            {
                NomeProjeto = ss.NomeProjeto,
                IdProjeto = ss.IdProjeto,
            }).ToList();

        foreach (var item in teste)
        {
            Projeto VMColab = new Projeto();
            VMColab.IdProjeto = item.IdProjeto;
            VMColab.NomeProjeto = item.NomeProjeto;
            ListaExemplo.Add(VMColab);
        }

        return Json(ListaExemplo);
    }

[View]

<div class="row">
    <div class="col-md-6">
        Nome Cliente:
        @Html.DropDownList("TabelaCliente", new SelectList(ViewBag.ListaClientes, "IdCliente", "NomeCliente"))
    </div>

    <div class="col-md-6">
        Nome Projeto
        @*@Html.DropDownList("TabelaProjeto", new SelectList(Enumerable.Empty<SelectListItem>(), "IdProjeto", "NomeProjeto"))*@
        @Html.DropDownList("TabelaProjeto", new SelectList(Enumerable.Empty<SelectListItem>(), "IdProjeto", "NomeProjeto"))
    </div>

[Javascript]

<script type="text/javascript">
$(document).ready(function () {
    $('#TabelaCliente').change(function () {
        var idCliente = $('#TabelaCliente').val();
        if (idCliente > 0) {
            $.post('@Url.Action("obterProjeto", "teste")', { 'idCliente': idCliente }, function (data) {
                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        $('#TabelaProjeto').append('<option value="' + data[i].idprojeto + '">' + data[i].nomeProjeto + '</option>');
                    }
                }

            });
        }
    });
});

1 answer

0


Before making the append, you must empty the dropdown. You can do with:

$('#TabelaProjeto').empty();

Put the code above before the for. The .empty() empties the element, that is, removes all content that it has.

For example, if I have a dropdown with options:

<select id="TabelaProjeto">
   <option></option>
   <option></option>
   <option></option>
</select>

When executing $('#TabelaProjeto').empty(), the result will be:

<select id="TabelaProjeto">
</select>

Browser other questions tagged

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