Problems when filling datatable ASP.NET

0

I'm having a little problem filling out a datatable from a WebMethod. The issue is that the array arrives in the browser console and the datatable in each column shows [object Object] in this way:

This is the WebMethod:

    [WebMethod]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
    public static List<Persona> ListarPersonas()
    {
        List<Persona> Lista = null;

        try
        {
            Lista = PersonaBL.getInstance().ListarPersonas();
        }
        catch (Exception ex)
        {
            Lista = new List<Persona>();
        }
        return Lista;
    }

And this is the code js:

$.ajax({
    url: 'FrmPersona.aspx/ListarPersonas',
    type: 'GET',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (data) {
        console.log(data.d);
        $.each(data, function (data) {
            var body = "<tr>";
            body += "<td>" + { data: [0] } + "</td>";
            body += "<td>" + { data: [1] } + "</td>";
            body += "<td>" + { data: [2] } + "</td>";
            body += "<td>" + { data: [3] } + "</td>";
            body += "</tr>";
            $("#datatable").append(body);
        })
        $("#datatable").DataTable(tabla);
    }
});

Any solution? I do not know what to do anymore, I've searched everywhere and I still can not fill it correctly.

    
asked by Kodake 23.12.2018 в 19:32
source

1 answer

0

The problem is that you are not accessing your array of objects correctly. You must correct your js code in the following way:

$.ajax({
    url: 'FrmPersona.aspx/ListarPersonas',
    type: 'GET',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (data) {
        console.log(data.d);
        $.each(data, function (index, value) {
            var body = "<tr>";
            body += "<td>" + { data[index].propiedad} + "</td>"; //Reemplazar propiedad
            body += "<td>" + { data[index].propiedad} + "</td>";//Reemplazar propiedad
            body += "<td>" + { data[index].propiedad} + "</td>";//Reemplazar propiedad
            body += "<td>" + { data[index].propiedad} + "</td>";//Reemplazar propiedad
            body += "</tr>";
            $("#datatable").append(body);
        })
        $("#datatable").DataTable(tabla);
    }
});

Important: You must replace "property" with the name of the properties you want to display. For example in the image I can see that one is called "IdPersona" and another "Nombre". On the other hand you could also replace data[index].propiedad with value.propiedad and it would still work. You can read the documentation to understand how it works. Greetings!

    
answered by 23.12.2018 в 22:02