How do I send data from a dynamic HTML table via json

0

I need to do something like the code below:

Here I create the table htmla dynamically:

$('#btnIncluirContato').on('click', function () {

    $('#tblContato tbody').append('<tr id=' + $('#ContatoID').val() + '>' +
    '<td class="NomeContato" id="NomeContato">' + $('#NomeContato').val() + '</td>' +
    '<td class="TelefoneContato" id="TelefoneContato">' + $('#TelefoneContato').val() + '</td>' +
     '<td class="remover" id="remover">' + '<a href="#"><img src="/Content/Images/excluirFlatRed.png" class="remover" /></a>' + '</td>' +
    '</tr>');

});

Here I send to the database via ajax:

 $("#btnFinalizar").click(function () {

    //Percorrer a tabela 
    var table = $('#tblContato');
    table.find('tr').each(function (indice) {

        $(this).find('td').each(function (indice) {

        });

    });

    //Setar campos inputs da Tela
    var _TBCliente = {
        'ID': $('#campoID').val(),
        'Nome': $('#campoNome').val(),
        'Idade': $('#campoIdade').val(),
        'TBContato':[]
    };

    //Adicionar os itens da Tabela de Contato
    _TBCliente.TBContato.push({

    });

    //Com o objeto populado eu vou enviar para o banco via $.ajax
});

The main question is how to get the data from the HTML table and popular the object that will be sent to a JsonResult method?

    
asked by anonymous 31.03.2016 / 22:17

1 answer

1

You can try this:

var dados  =  [];
var i     =  0;
var table = $('#tblContato');
table.find('tr').each(function () {
   dados[i]['id']  =  $( this ).find( 'td:nth-child(1)' ).text();
   dados[i]['nome']  =  $( this ).find( 'td:nth-child(2)' ).text();
   dados[i]['idade']  =  $( this ).find( 'td:nth-child(3)' ).text();
   dados[i]['contato']  =  $( this ).find( 'td:nth-child(4)' ).text();
   i++;
});
$.ajax({
   type: "POST",
   data: {meusDados:dados},
   url: "http://seusite.com.br/processarPost",
   success: function( data ){
       alert( 'Enviou' )
   },
   error: function (request, status, error) {
      alert(request.responseText);
   }
});

Change the nth-child pseudo-class to suit you.

I hope it helps.

    
31.03.2016 / 22:53