Load city select after state select

0

I have this HTML, and I would like that when the user selects the state, it loads the data of the city of the selected state:

 <label asp-for="Cidade" class="col-md-1 control-label" style="text-align:left;"></label>
                            <div class="col-md-3">
                                <select asp-for="Cidade" asp-items="@Model.CodigoMunicipioList" id="cbmunicipio" class="form-control"> <option disabled selected>Selecione o Município</option></select>
                                <span asp-validation-for="Cidade" class="text-danger"></span>
                            </div>
                            <label asp-for="UF" class="col-md-1 control-label" style="text-align:left;"></label>
                            <div class="col-md-2">
                                <select asp-for="UF" class="form-control">
                                    <option disabled selected>Selecione</option>
                                    <option value="AC">AC</option>
                                    <option value="AL">AL</option>
                                    <option value="AM">AM</option>
                                    <option value="AP">AP</option>
                                    <option value="BA">BA</option>
                                    <option value="CE">CE</option>
                                    <option value="DF">DF</option>
                                    <option value="ES">ES</option>
                                    <option value="GO">GO</option>
                                    <option value="MA">MA</option>
                                    <option value="MG">MG</option>
                                    <option value="MS">MS</option>
                                    <option value="MT">MT</option>
                                    <option value="PA">PA</option>
                                    <option value="PB">PB</option>
                                    <option value="PE">PE</option>
                                    <option value="PI">PI</option>
                                    <option value="PR">PR</option>
                                    <option value="RJ">RJ</option>
                                    <option value="RN">RN</option>
                                    <option value="RS">RS</option>
                                    <option value="RO">RO</option>
                                    <option value="RR">RR</option>
                                    <option value="SC">SC</option>
                                    <option value="SE">SE</option>
                                    <option value="SP">SP</option>
                                    <option value="TO">TO</option>
                                </select>
                                <span asp-validation-for="UF" class="text-danger"></span>
                            </div>

And here's how I load the data:

  var cidade = db.MunicipioIBGE.OrderBy(c => c.NomeMunicipio).Select(y => new { Id = y.CodigoIBGE, Value = y.NomeMunicipio });
            model.CodigoMunicipioList = new SelectList(cidade, "Id", "Value");

But this does not filter.

This is the function where you have where

  [HttpGet]
    public ActionResult BuscaCidades(string estado)
    {
        var cidade = db.MunicipioIBGE.OrderBy(c => c.NomeMunicipio).Where(c => c.Estado == estado).Select(y => new { Id = y.CodigoIBGE, Value = y.NomeMunicipio });

        return Json(new { cidade });
    }

And here is the CarregaCidade function:

function CarregaCidade(estado) { 
    //var estado = $("#UF").val();
    $.ajax({
        type: 'GET',
        data: estado,
        url: '/Empresas/BuscaCidades',
        dataType: 'json',
        success: function (dados) {
            if (dados !== null) {
                var selectbox = $('#cbmunicipio');
                $('<option>').val("0").text("Selecione um município").appendTo(selectbox);
                $.each(dados, function (i, d) {
                    $('<option>').val(d.Id).text(d.value).appendTo(selectbox);
                })


            }
        },
        error: function () {
            console.log("Falha de enviar AJAX");
        }
    })
}
    
asked by anonymous 04.12.2018 / 16:19

2 answers

2

When the user selects a state, he has to fire an ajax request, which is just below

Ajax:

$("#UF").on("change", function () { 
   var estado = $("#UF option:selected").val(); 
   $.ajax({ 
   type: 'GET', 
   data: { estado: estado }, 
   url: '/Empresas/BuscaCidades', 
   dataType: 'json', 
   success: function (dados) { 
   if (dados !== null) { 

      var selectbox = $('#cbmunicipio'); 
      $("#cbmunicipio").empty() 
          $('<option>').val("0").text("Selecione o Município").appendTo(selectbox); 
          $.each(dados.cidade, function (i, d) { 
          $('<option>').val(d.id).text(d.value).appendTo(selectbox); 
   }) 


    } 
}, 

Controller

[HttpGet] 
public ActionResult BuscaCidades(string estado) 
{ 
   var cidade = db.MunicipioIBGE.OrderBy(c => c.NomeMunicipio).Where(c => c.Estado == estado).Select(y => new { Id = y.CodigoIBGE, Value = y.NomeMunicipio }).ToList(); 

   return Json(new { cidade }); 
}
    
04.12.2018 / 16:31
1

You can do the following, a function to pass the State Id to bring the cities of it, see the example below where I pass the system id and load its categories:

        <div id="divSistemas" class="form-group row">
            <label class="col-sm-2 form-control-label">Sistema</label>
            <div class="col-sm-10">                   
                @Html.DropDownList("id_sistemas", ViewBag.id_sistama as SelectList, "", htmlAttributes: new { @class = "form-control", onchange = "PegaCategoria(this.value)" })
            </div>
        </div>
        <div id="divCategoria" class="form-group row">
            <label class="col-sm-2 form-control-label">Categoria</label>
            <div class="col-sm-10">
                @Html.DropDownList("id_categoria_atendimento", ViewBag.id_categoria as SelectList, "", htmlAttributes: new { @class = "form-control", onChange = "GetSubCategorias(this.value)" })
            </div>
        </div>


function PegaCategoria(idSistema) {
        $("#id_categoria_atendimento").empty();
        $("#id_categoria_atendimento").append('<option value=""></option>');
        $.ajax({
            type: "POST",
            url: '@Url.Action("PegaCategoria")',
            dataType: "json",
            data: "{idSistema: '" + idSistema + "'}",
            contentType: "application/json; charset=utf-8",
            success: function (sist) {
                $.each(sist, function (i, state) {
                    $("#id_categoria_atendimento").append('<option value="' + state.Value + '">' + state.Text + '</option>');
                });
                GetSubCategorias($("#id_categoria_atendimento").val());

            },
            error: function (ex) {
                //alert('Failed to retrieve states.' + ex);
            }
        });
    }

In the controller I get the system id and do a simple search.

    [WebMethod]
    public JsonResult PegaCategoria(int idSistema)
    {
        return Json(new SelectList(db.tbl_sistema_categoria_atendimento
            .Where(x => x.id_sistema == idSistema && x.tbl_categoria_atendimento.ativo == true)
            .OrderBy(x => x.tbl_categoria_atendimento.categoria_atendimento)
            .Select(x => x.tbl_categoria_atendimento), "id_categoria_atendimento", "categoria_atendimento"));
    }
    
05.12.2018 / 17:31