Popular table using Json

Asked

Viewed 2,265 times

0

I’m having a hard time getting a table in my code cshtml. I’m new to the ajax and I’m not really understanding what I need to do with the data that came from the bank.

Just follow my code:

Code cshtml:

<div><table id="datagrid"></table></div>

My Controller:

public JsonResult Buscar(string fornecedor)
{
    JsonResult json = new JsonResult();
    UsuarioViewModel usuarioViewModel = new UsuarioViewModel();
    int iCnpj;
    bool resultado = int.TryParse(fornecedor, out iCnpj);
    usuarioViewModel.FornecedorBusca = fornecedor;
    if (resultado)
    {
        List<Fornecedor> listFornecedor = new BuscaDadosFornecedorBo().BuscaRequisicaoFornecedorBo(usuarioViewModel.FornecedorBusca, "");
        usuarioViewModel.ListaFornecedorViewModels = listFornecedor;
    }
    json.Data = usuarioViewModel.ListaFornecedorViewModels;
    return json;
}

My code jQuery:

$(document).ready(function () {
        //Post para Buscar os fornecedores
    $("#btnBuscar").on("click", function () {
        $.ajax({
            type: 'POST',
            url: 'Buscar',
            data: {
                fornecedor: $("#FornecedorBusca").val()
            },
            dataType: 'json',
            success: function (data) {
                debugger;
                console.log(data);
            },
            error: function (data) {
                debugger;
                alert('Error' + data);
            }
        });
    });

And this is the return of JSON (With fictitious data):

0: Object:
Codigocnpj: "88.643.168/0001-66"
Municipio: "Valinhos"
RazaoSocial: "Copyright 2007-2015 - Gerador de CNPJ"


1: Object: 
Codigocnpj: "85.558.272/0001-64"
Municipio: "Campinas"
RazaoSocial: "Gerador de CNPJ - Gerar CNPJ Válido"

2 answers

2

By the look of the data you put in you get a array with objects within.

I mean, something like this:

data = [{
    Codigocnpj: "88.643.168/0001-66",
    Municipio: "Valinhos",
    RazaoSocial: "Copyright 2007-2015 - Gerador de CNPJ"
}, {
    Codigocnpj: "85.558.272/0001-64",
    Municipio: "Campinas",
    RazaoSocial: "Gerador de CNPJ - Gerar CNPJ Válido"
}];

If you want to put this in a table you can create a table with 2 cycles for (or . foreach()` as in the example below). The first for each line, and the second for each cell within that line.

var tabela = document.getElementById('datagrid');
data.forEach(function (obj) {
    var tr = document.createElement('tr');
    Object.keys(obj).forEach(function (chave) {
        var td = document.createElement('td');
        td.innerHTML = obj[chave];
        tr.appendChild(td);
    });
    tabela.appendChild(tr);
});

jsFiddle: http://jsfiddle.net/c46bfho7/2

0


I found a very efficient way to create the table with the data returned from the Controller. But first, I want to thank Sergio for his reply. Thanks for the support. Follow the code:

$.ajax({
                type: 'POST',
                url: 'Buscar',
                data: {fornecedor: $("#FornecedorBusca").val()},
                dataType: 'json',
                success: function (data) {
                    debugger;
                    if (!data) {
                        alert('Fornecedor não encontrado. Por favor verifiquei e tente novamente.');
                    } else {
                        var tabela = $("#datagrid");
                        var rows = "";
                        tabela.find("tbody td").remove();
                        _.each(data, function (item) {
                            rows += "<tr>";
                            rows += " <td>" + item.Codigocnpj + "</td>";
                            rows += " <td>" + item.RazaoSocial + "</td>";
                            rows += " <td>" + item.Municipio + "</td>";
                            rows += " <td> <input type='checkbox' /> </td>";
                            rows += "</tr>";
                        });
                        //tabela.find("tbody").append(rows);
                        tabela.find("tbody").html(rows);
                    }
                },
                error: function (data) {
                    debugger;
                    alert('Error');
                }
            });

In case you’re wondering, I used the

_.each(date, Function (item)

Well, I found the concept of iteration of Underscorjs, if you like, just download and import into the VCS project. Hugs.

Browser other questions tagged

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