Load select via ajax

Asked

Viewed 223 times

0

I am trying to load a select via ajax, following as I am doing: HTML:

<select id="cbplanos" class="form-control"></select>

Controller Code:

public async Task<IActionResult> Load()
    {
        var lista = _context.PlanosServicos
        .Select(x => new { x.Id, x.Descricao });

        return Json(new { Resultado = lista });

}

And here’s the AJAX code:

function ListarItens() {
    var url = "/PessoasServicos/Load";

    $.ajax({
        type: "get",
        url: "/PessoasServicos/Load",
        data: { tipos: $("#cbplanos").val() },
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            var selectbox = $('#cbplanos');
            $.each(data, function (i, d) {
                selectbox.append('<option value="' + d.Id + '">' + d.Descricao + '</option>');
            });
        }
    });
}

But he’s not bringing me values. What I’m going through wrong?

  • Already inspected the object "date" in success? Seems to me you should wear data.Resultado in the each

  • I tried this way, but continued with the same problem.

  • But if you inspect the "date" object, the data is being returned?

  • It is now showing two items that are in this table Planosservicos, but in select appears as Undefined.

1 answer

1


When you pass the Json new Upshot, the field that will have the values of the list. Just do it this way:

public async Task<IActionResult> Load()
{
    var resultado = _context.PlanosServicos
    .Select(x => new { x.Id, x.Descricao });

    return Json(resultado);    
}

In the script:

function ListarItens() {
    var url = "/PessoasServicos/Load";
    var selectbox = $('#cbplanos');
    selectbox.html("<option value='0'>Selecione</option>");
    $.ajax({
        type: "get",
        url: url,
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {

            $.each(data, function (i, d) {
                selectbox.append('<option value="' + d.id + '">' + d.descricao + '</option>');
            });
        }
    });
}
  • It appears two data in select, but I appear Undefined.

  • try switching d.Id for i.Id

  • How so two dice?

  • It worked, rs, was passing wrong in ajax, was passing Id, and Descricao, was just switching to lowercase, and put the same return helped and worked, thank you. Only there’s a problem, every time I call the function it charges, how can I put to clean ?

  • I edited the question by cleaning it at each request; About the id I think in another question you asked about this, it’s a matter of the "contract", it returns the tiny properties, has how to change it,

Browser other questions tagged

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