Home > Back-end >  How can I retrieve the content of my jquery datatable in c#?
How can I retrieve the content of my jquery datatable in c#?

Time:01-28

I have an HTML table that I'm converting into datatable. In this datatable, I can edit a value in a cell. I want to attach a "save" button to this datatable and once a user clicks it then it should save the content of the datatable into SQL Server database.

My problem is, I couldn't find out how I can extract the data from js:datatable object into c#? I think I need to use something like below but it doesn't work and returning error. "Cannot read properties of undefined (reading 'type')". Here is the code:

<table id="tb_voteProjects"  cellspacing="0" >
            <%=getColumnHeaders()%> 
            <%=getActiveData()%> 
</table>
...

var table = $('#tb_voteProjects').DataTable({
...,
buttons: [
...
{
    text: 'Save',
    action: function ( e, dt, node, config ) {
    $.ajax({
            type: "POST",
            url: 'Ranking.aspx/SaveRanks',
            data: {table}, //HOW TO SEND THE TABLE CONTENT INTO C# ???
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                window.location.reload();
            },
            error: function (e){
                Console.log(e);
            }
    });
}
                        

Any help would be appreciated.

Thanks.

Edit1: using ...data: table.rows().data()..., instead of ...data:table..., in my ajax didn't fix the issue.

CodePudding user response:

You can use the dt object in your action function - that represents the DataTables API for your table.

From there you can use dt.rows().data().toArray(). This creates an array containing each row of table data in a sub-array.

You can then convert that JavaScript array to a JSON string:

data: JSON.stringify( dt.rows().data().toArray() ),

I assume you already know how to use your C# server code to retrieve the JSON payload from the body of the POST request.


Reference:

  • Related