Transfer table data to the server side

Transfer table data to the server side

BTalayiBTalayi Posts: 18Questions: 4Answers: 0
edited March 2020 in Free community support

Hi every one,

Here is the scenario in my project: user updates the data table on the client side and then will save data on a shared folder as a text or csv file. I'm using MVC and C# and need to find a way to transform data from client side to the server. My thought is sending the table data through an ajax call and editor button. here is the example I found that used ajax to export csv:

{
 text: 'Export CSV',
     action: function (e, dt, node, config) {
          $.ajax({
            "url": "api/export",
            "data": dt.ajax.params(),
            "success": function (res, status, xhr) {
            var csvData = new Blob([res], { type: 'text/csv;charset=utf-8;' });
            var csvURL = window.URL.createObjectURL(csvData);
            var tempLink = document.createElement('a');
            tempLink.href = csvURL;
            tempLink.setAttribute('download', 'data.csv');
            tempLink.click();
            },
     "error": function (xhr, error, thrown) {
     error(xhr, error, thrown);
         }
     });
     }
},                       

Is there any way to change this function to post table data to a mvc controller or web api and from there create a text file in a desired location?
That would be great if you guys help me to find a way to fix this.
Thanks

Replies

  • rf1234rf1234 Posts: 3,021Questions: 88Answers: 421
    edited March 2020

    I would get the data of the rows of the entire table
    then JSON.stringify them and send them to the server via ajax call
    Then I would write the csv or text file server side which is very easy.

    Here is a custom button that sends all rows to the server as an array of objects that is JSON stringified. The button is called "sendTable" and its label is "Send Table to Server". You can use it like any predefined button in your data table. But you must define it before the data table is being initialized.

    $.fn.dataTable.ext.buttons.sendTable = {
        text: "Send Table to Server",
        action: function ( e, dt, button, config ) {
            $.ajax({
                type: "POST",
                url: 'api/export',
                data: {
                    table: JSON.stringify(dt.rows().data().toArray())
                },
                success: function () {
                    // do something
                }
            });
        }
    };
    
    //your data Table definition follows and then the buttons part of it:
    ....
    buttons: [
           "sendTable ",
           "colvis" 
    ],
    ...
    
    

    Server side you just json_decode what you received and you can write your file.

  • rf1234rf1234 Posts: 3,021Questions: 88Answers: 421

    I just tried it myself. This is what

    var table = dt.rows().data().toArray();
    

    produces:


    It is an array of twenty rows.

    The table has over 100,000 rows! Why only 20? Pagination is set to 20 and the table is a serverSide data table.

    Removed "serverSide" and waited about half an hour for the table to load (using XAMPP on an old PC ...). And yes: then I stopped waiting. The PC is too old. I assume that not using ServerSide the entire data table should be exportable not only what you see on the page.

  • BTalayiBTalayi Posts: 18Questions: 4Answers: 0
    edited March 2020

    Thank you for your response @rf1234

    I tried your script but my table object is still empty:
    here is my ajax call:

      $.fn.dataTable.ext.buttons.sendTable = {
                text: "Send Table to Server",
                 action: function (e, dt, button, config) {
                    var tbl = dt.rows().data().toArray();
                    $.ajax({
                        "type": "POST",
                        "url": '/api/export',
                        "dataType": 'json',
                        "data": JSON.stringify(tbl),
                        "success": function (data, status, xhr) {
                            console.log(data);
                        }
                        ,
                        "error": function (xhr, error, thrown) {
                            console.log('Error in Operation');
                        }
                    });
                }
            };
     
    

    and here is my web api:

    namespace validation.Controllers
    {
        public class tbl
        {
            public string asset_name { get; set; }
            public int num_asset_sticker { get; set; }
            public int num_print { get; set; }
            public string serial_number { get; set; }
            public int num_sn_sticker { get; set; }
            public string environment { get; set; }
            public string printer { get; set; }
        }
        public class ExportController : ApiController
        {
            [HttpPost]
            public IHttpActionResult Post(tbl tdata)
            {
               
                if (tdata != null)
                {
    
                    Console.WriteLine(tdata);
                    return Ok(tdata);
                }
    
                return NotFound();
            }
        }
    }
    
    

    and here is the console:

    and web api debug is also showing null:

    I'no not sure where I did it wrong!

  • rf1234rf1234 Posts: 3,021Questions: 88Answers: 421
    edited March 2020

    Mmhh... with my code you are sending an array of objects to the server. If your controller expects an object you can simply drop the "toArray()" piece.

    Try this ... and use your debugger please to see what you receive at the back end:

    var tbl = dt.rows().data();
    

    If you are sending an array as in my example above make sure you json_decode the values posted on the server! Don't know how to do this in .NET.

    I never send an object (only arrays of objects). So I don't know how to deal with it at the back end. But it should also need to be json_decoded because it gets JSON.stringified at the front end.

  • BTalayiBTalayi Posts: 18Questions: 4Answers: 0

    I found the solution!

    Thank you @rf1234 for your help!
    I just needed to create a model with a list of main model and then post entire table to my web api.

    public class CreateUserViewModel
    {
       public int Id {set;get;}
       public string Name {set;get;}  
       public List<TagViewModel> Tags {set;get;}
    }
    public class TagViewModel
    {
      public int Id {set;get;}
      public string Code {set;get;}
    }
    

    Here is the link:
    https://stackoverflow.com/questions/20226169/how-to-pass-json-post-data-to-web-api-method-as-an-object

    my final ajax call function:

    {
    text: "Send Table to Server",
    action: function () {
             var tblTest = { tbl: table.rows().data().toArray() };
               $.ajax({
                     type: "POST",
                    data: JSON.stringify(tblTest),
                    url: "api/export/send",
                    contentType: "application/json"
                    }).done(function (res) {
                       console.log('res', res);
                   });
                      }
    }
    
    
  • rf1234rf1234 Posts: 3,021Questions: 88Answers: 421

    Glad you got it working!
    This ajax stuff can be really difficult. Yesterday I was searching for hours because I got a return value from the server (json_encoded object with a string and an array of objects in it), I could even see it in Chrome but couldn't get a handle on it with Javascript. It turned out that I forgot one line in my ajax call. No error message, nothing. I was about to go crazy ...

    This is the line I missed in the ajax call:

    dataType: "json",
    
This discussion has been closed.