Fill Dropdown from the selection of another Dropdown

Asked

Viewed 706 times

1

Guys, I’m trying to fill one DropDown from the selection of another DropDown, basically, when the user selects a state in a DropDown, cities of this state must be displayed in another DropDown, dynamically.

I have the following code:

VIEW

<div class="col-lg-2">
    <div class="form-group">
        <label class="control-label">
            Departamento:
        </label>
        <div id="EstadoDifBrasil">                                
            @this.AutoSelect(x => x.StatePar).Class("form-control required").FirstOption("", "Selecione uma opção")                                
        </div>
    </div>
</div>
<div class="col-lg-3">
    <div class="form-group">
        <label class="control-label">
            Cidade:
        </label>
        <div id="CidadeDifBrasil">
            @this.AutoSelect(x => x.CityPar).Class("form-control required").FirstOption("", "Selecione uma opção")
        </div>
    </div>
</div>

$("#StatePar").change(function () {
    var idStatePar = $("#StatePar").val();
    $.post("@Url.Action(MVC.Escritorio.Clientes.VerificarCidadeDifBr())", { codCitySel: idStatePar })
        .success(function (result) {
            alert(result.length);
        })
        .error(function (ex) {
            alert('Erro ' + ex);
        })
});

CONTROLLER

[HttpGet]
public virtual JsonResult VerificarCidadeDifBr(int codCitySel)
{
    var xpto = new List<TCity>();
    xpto = TCity.ListAllCities().Where(x => x.State.Id == codCitySel).OrderBy(x => x.Name).ToList(); //.ToSelectList(x => x.Id, x => x.Name);

    return Json(xpto, JsonRequestBehavior.AllowGet);
}

In the controller I can list the cities of the state I select, but I cannot return to the view via Json, only of the alert "Erro: [object Object]".

Someone has some light, please?

Thank you and great week!

  • Your method is get and you’re using $.post, tried to change to get?

  • @Filipeoliveira, I tried to change both to GET and POST and the problem persists the same =/. Thank you!

  • Have you tried using $.ajax? You can also check the error by the Chrome console if there is a script error or even check what was the return of Request through the "Network" tab of Chrome(F12). So you will be sure about what was returned from server error if there was an error. Also if you pass this function in "error", you will have more details: Function( jqXHR, textStatus, errorThrown ) {}

1 answer

0

I think you have complicated a lot. You could have written the Ajax event like this:

@section Scripts 
{
    <script>
        $("#StatePar").change(function () {
            $.ajax({
                url: "/Departamentos/CidadesPorDepartamento/" + id,
                success: function (data) {
                    $("#CityPar").empty();
                    $("#CityPar").append('<option value>Selecione...</option>');
                    $.each(data, function (index, element) {
                        $("#CityPar").append('<option value="' + element.CityId + '">' + element.Name + '</option>');
                    });
                }
            });
        });
    </script>
}

Action in Controller:

[HttpGet]
public virtual JsonResult CidadesPorDepartamento(int id)
{
    var xpto = TCity.ListAllCities()
                    .Where(x => x.State.Id == codCitySel)
                    .OrderBy(x => x.Name)
                    .Select(x => new { CityId = x.Id, Name = x.Name })
                    .ToList(); //.ToSelectList(x => x.Id, x => x.Name);

    return Json(xpto, JsonRequestBehavior.AllowGet);
}

Browser other questions tagged

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