Checkbox does not load returned data in JSON

Asked

Viewed 64 times

0

I’m having trouble loading a checkbox (<select>) using C# MVC with Json. The method returns the complete list with objects, but does not click on the checkbox.

Man Controller:

public ActionResult SelecionarRepresentante()
{
    var lista = Dao.SelecionarRepresentante().ToList();
    return Json(new { lista }, JsonRequestBehavior.AllowGet);
}

Man Model:

public List<Representante> SelecionarRepresentante()
{
    string consulta = @" SELECT
                            A3_COD,
                            A3_NOME
                        FROM
                            SA3010 SA3
                        WHERE
                            SA3.D_E_L_E_T_ = ''
                            AND A3_SUPER = ''
                            AND A3_COD IN
                                (SELECT DISTINCT A1_VEND FROM SA1010 )
                        ORDER BY
                            A3_NOME";

    using (var conn = new SqlConnection(conexaoProtheus))
    {
        var cmd = new SqlCommand(consulta, conn);
        List<Representante> dados = new List<Representante>();
        Representante p = null;
        try
        {
            conn.Open();
            using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                while (reader.Read())
                {
                    p = new Representante();
                    p.codigoRepresentante = reader["A3_COD"].ToString();
                    p.nome = reader["A3_NOME"].ToString();

                    dados.Add(p);
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            conn.Close();
        }
        return dados;
    }
}

Man Javascript:

$(document).ready(function () {
        $.ajax({
            type: "get",
            url:'/Gerenciamento/UsuarioExterno/SelecionarRepresentante',
            data: { representante: $("#representante").val() },
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (obj) {
                console.log(obj);
                if (obj != null) {
                    var data = obj.data;
                    var selectbox = $('#representante');
                    selectbox.find('option').remove();
                    $.each(data, function (i, d) {
                       $('<option>').val(d.codigoRepresentante).text(d.nome).appendTo(selectbox);
                    });
                }
            }
        });
});

My View:

<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="~/Areas/Gerenciamento/Script/usuarioExterno/usuarioexternocadastro.js"></script>
<div id='formulario'>
    <h2>Usuário Externo Cadastro</h2>
    <br />

    @using (Html.BeginForm("Salvar", "UsuarioExterno", FormMethod.Post, new { Area = "Gerenciamento" }))
    {

    <fieldset class="grupo">

        <div class="campo">
            <label class="col-md-2 control-label">Codigo Representante: </label>
            <div class="col-md-6">
                <select class="form-control" name="representante" id="representante"></select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-md-2 control-label">Empresa: </label>
            <div class="col-md-6">
                <select class="form-control" name="empresa" id="empresa"></select>
            </div>
        </div>
    </fieldset>
</div>
  • Already seen if it returns any error in the console?

  • does not return error. , and still returns the object list

  • Put that console.log(obj); inside the IF and see if it prints

  • within if and within $.each it returns the object list. But d.codigoRepresentant does not print

  • lista:[{"codigoRepresentante":"000041","nome":"A E FILHO E ESTEVES REPRESENTACAO COMERCIAL LTDA ME"},{"codigoRepresentante":"000018","nome":"A. M. LUZ REPRESENTACOES COMERCIAIS LTDA"},

  • The nome prints?

  • Puts console.log(selectbox.length); shortly after var selectbox = $('#representante');... have to return 1 on the console.

  • $.ajax({ url: "/Management/External/Selector Presenter", Success: Function (date) { $("#representative"). Empty(); $("#representative"). append('<option value>Select...</option>'); $.each(date, Function (i, element) { $("#representative"). append('<option value="' + element.codeRepresentante + '">' + element.name + '</option>'); }); } });

  • If solved tá blz.

  • thanks friend. Hugs

Show 5 more comments

1 answer

0


Revolvi modifying. It was like this...

$(document).ready(function () {
    $.ajax({
        url: "/Gerenciamento/UsuarioExterno/SelecionarRepresentante",
        success: function (data) {
            $("#representante").empty();
            $("#representante").append('<option value>Selecione...</option>');
            $.each(data, function (i, element) {
                $("#representante").append('<option value="' + element.codigoRepresentante + '">' + element.nome + '</option>');
            });
        }
    });
});

Browser other questions tagged

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