Fill fields with json function return with jquery

Asked

Viewed 8,248 times

2

I have this method in Controller

[HttpPost]
public JsonResult PreencheEndereco(string _cpf)
{
    AgaxturCmsEntities db = new AgaxturCmsEntities();

    try
    {
        var Result = (from a in db.TB_CLIENTES
                      where a.CdCliente == "1" && a.CPF == _cpf
                        select new {

                           a.Endereco,
                           a.Numero,
                           a.CEP,
                           a.Complmento,
                           a.Telefone,
                           a.Celular

                        }).ToList();

        return Json(new { Result }, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        return Json(new { Result = ex.Message }, JsonRequestBehavior.AllowGet);
    }
}

What I need is to do a jquery function and fill in these 6 fields returned by the function. This is my function skeleton, but as I do now to fill?

$(function () {
    $("#btnEndereco").click(function () {
        $.ajax({
            url: '/Passo/PreencheEndereco',
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            type: "POST",
            data: JSON.stringify({ _cpf: $("#CPF").val() }),
            success: function (data) {

                $(data.Result).each(function () {
                    $("#endereco").val(this.Endereco);
                });
            },
            error: function (error) {
            }
        });
    });
});

On this line I think I should insert the bank’s return into the field, it doesn’t work. I wonder if anything else is needed:

$("#endereco").val(this.Endereco);

These are the fields that need to be filled in, in HTML. I put an id for each of them, to take jquery. Id’s are for inputs.

<div class="form-group">
    <div class="grid_4">
        <label>CEP</label>
    </div>
    <div class="grid_14">
        <input id="cep" type="number" name="txtCep" class="grid_3  required" placeholder="00000-000" required />
    </div>
</div>
<div class="form-group">
    <div class="grid_4">
        <label>Endereço</label>
    </div>
    <div class="grid_14">
        <input id="logradouro" type="text" name="txtLogradouro" class="grid_14 required" placeholder="Nome completo" required />
    </div>
</div>
<div class="form-group">
    <div class="grid_4">
        <label>Número</label>
    </div>
    <div class="grid_4">
        <input id="numero" type="text" name="txtNumero" class="grid_3  required" required />
    </div>
    <div class="grid_2">
        <label>Complemento</label>
    </div>
    <div class="grid_8">
        <input id="complemento" type="text" name="txtComplemento" class="grid_8  required" required />
    </div>
</div>
<div class="form-group">
    <div class="grid_4">
        <label>Telefone</label>
    </div>
    <div class="grid_6">
        <input id="telefone" type="text" name="txtTelefone" class="grid_6  required" required />
    </div>
    <div class="grid_2">
        <label>Celular</label>
    </div>
    <div class="grid_6">
        <input id="celular" type="text" name="txtCelular" class="grid_6  required" required />
    </div>
</div>

2 answers

3

On your controller, remove the Httppost attribute from the action, if the intention is to call via GET. By returning it, allowing Json to be returned via GET I suppose that is the intention.

The view you could do so:

<!DOCTYPE html>
<html>
<head>
    <title>title</title>
    <script type="text/javascript" src="/Scripts/jquery-2.1.0.min.js"></script>
    <script type="text/javascript">
        function PreencheEndereco() {

            $.ajax({
                url: '/Home/PreencheEndereco',
                data: { _cpf: $("#CPF").val() },
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                type: "GET",
                success: function (data) {

                    var result = data.Result;
                    for (var it = 0; it < result.length; it++) {
                        $("#tbl > tbody").append(
                            "<tr>" +
                            "    <th>" + result[it].Endereco + "</th>" +
                            "    <th>" + result[it].Numero + "</th>" +
                            "    <th>" + result[it].CEP + "</th>" +
                            "    <th>" + result[it].Complmento + "</th>" +
                            "    <th>" + result[it].Telefone + "</th>" +
                            "    <th>" + result[it].Celular + "</th>" +
                            "</tr>"
                            );

                    }
                },
                error: function (error) {

                }
            });
        }

        $(function () {
            $("#btn").on("click", function () {
                PreencheEndereco();
            });
        });
    </script>
</head>
    <body>
        <div>
            CPF: <input type="text" id="CPF"/>
        </div>
        <button id="btn">Preencher dados</button>
        <table id="tbl">
            <thead>
                <tr>
                    <th>Endereco</th>
                    <th>Numero</th>
                    <th>CEP</th>
                    <th>Complmento</th>
                    <th>Telefone</th>
                    <th>Celular</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </body>
</html>

In this example, when you click the button, it will send the CPF that is written in the text box, do the query you have in the controller, and then with the Json that returns, it will fill the existing table just below the button with the values that come from the database.

  • I’m sorry for my ignorance. Since you put everything on TR and TH, I was a bit confused. I still get stuck with jquery. In my Html fields are organized with divs.

  • @pnet Do you mean that the fields already exist on the screen? You could instead construct the fields dynamically, the same way I did with the TD, just take out the TD and put an input.

-3

Solved. BIOS error. There was a div with the same name as the address id and so I think jquery went a little crazy and didn’t know who to fill. Is working.

  • 1

    Miguel Angelo’s code is a good approach for you to refactor your code and get more quality of it

Browser other questions tagged

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