Upload select via ajax

0

I'm trying to load a select via ajax, here's how I'm 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 is not bringing me the values. What am I missing?

    
asked by anonymous 29.06.2018 / 14:22

1 answer

1

When you pass in Json new Result , this field will have the values in 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);    
}

No 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>');
            });
        }
    });
}
    
29.06.2018 / 14:27