Load select city after selecting state

Asked

Viewed 781 times

0

I have this HTML, and would like when the user selects the state, it loads the city data 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");

Only it won’t filter.

This is the function where the 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 the function CarregaCidade:

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");
        }
    })
}
  • are you sure the request is coming, @marianac_costa? I mean, some request is being sent to where does this "var company" your?

  • @gabrielfalieri I haven’t done it in ajax yet, because I don’t know how to do, so I need the user to select the state, he selects the city, and there’s just how I carry all, now I need to filter by state.

  • I’ll put the answer there for you :)

  • @gabrielfalieri thank you

  • Look here, let me know

  • @gabrielfalieri edited the question, so you can understand what is happening.

Show 2 more comments

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 }); 
}
  • I’m trying to pass the state but it’s always returning null, I’ve tried to catch the state: var estado = $("#UF").val(); and calling the function so: <select asp-for="UF" class="form-control" id="UF" onchange="CarregaCidade(this.value);" > always go null, I’ll add on question as I’m trying to do.

  • I tried to get the UF that way too var estado = $("#UF option:selected").val(); only you always get null

  • Mariana, both ways have to work, especially the second...

  • Is it because I’m calling on onchange ?

  • I thought about it, it might be that he giving in to jquery

1

You can do the following, a function to pass the State Id to bring the cities of the same, see the example below where I pass the system id and load your 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"));
    }

Browser other questions tagged

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