JustLearning JustLearning - 5 months ago 39
JSON Question

Posting jquery datatable data to server in JSON format

I know this question has been asked numerous times on SO and on the datatables site, but i cannot get it to work using the solutions provided.

I am building my datatable on the client side and now want to post the client data to my wep api controller in json format.

The client side is working correctly when it comes to adding/deleting rows.
But when i try create my JSON using:

var table = $('#detailTable').DataTable();
var details = JSON.stringify(table.rows().data().toArray());

I am getting the following result:


so basically i am missing column names in my JSON object, thus the web api is failing to pick it up and convert it to:

List<ReceiptEntryViewModel> ReceiptDetails

So how can i get the datatables to generate a JSON in the following format:



If you just want to collect the column names and use them as property names in the JSON, then you can build an array of column names this way :

var fieldNames =  [], json = []
table.settings().columns()[0].forEach(function(index) {

I am using text() to filter out any HTML. Then do as above but iterate over each row instead, and construct a JSON item for each row using the collected fieldNames :

table.rows().data().toArray().forEach(function(row) {
  var item = {}
  row.forEach(function(content, index) {
     item[fieldNames[index]] = content

Now you have a valid JSON you can stringify and send to the server.

Small sample demo -> http://jsfiddle.net/5j9wgorj/

Note that this is just an example. If you have larger datasets you should avoid forEach and use for-loops instead. Also there should be no need for blindly rebuilding an array of header names since you, the developer, know both column names and what you want the properties to be named as beforehand.