Popular table using Json

0

I'm having trouble populating a table in my code cshtml . I'm new to ajax and I'm not fully understanding what I need to do with the data that came from the bank.

Here is 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 jQuery code:

$(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 dummy 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"
    
asked by anonymous 18.09.2015 / 20:08

2 answers

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 response. Thanks for the support. Here is 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');
                }
            });

If you are wondering why I used

  

_. each (data, function (item)

Well, I found the iteration concept of UnderscorJS interesting, if you want, just download and import into the vcs project. Hugs.

    
20.09.2015 / 22:42
2

For the data you put you get an array with objects inside.

That is, 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 the table with 2 cycles for (or .forEach () 'as in the example below). The first for each row, and the second for each cell within that row.

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: link

    
18.09.2015 / 20:17