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:
[["11046","ABC","bis","123","123",15129]]
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:
[["ItemId":"11046","ItemCode":"ABC","ItemName":"bis","Price":"123","Quantity":"123","Total":15129]]
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) {
fieldNames.push($(table.column(index).header()).text())
})
I am using text()
to filter out any HTML. Then do as above but iterate over each row instead, and construct an object literal (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
})
json.push(item)
})
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.
Update with the solution it ended up to be. The contortions with building a JSON can be avoided if the dataTable itself is prepared for using JSON. Define a columns
section :
var table = $('#example').DataTable({
columns : [
{ data : 'myField' }
]
})
And insert new rows as JSON / literals :
table.row.add({ myField: 'some value' }).draw()
Now
JSON.stringify( table.rows().data().toArray() )
Will return a valid JSON string that can be passed to the serverscript.
demo -> http://jsfiddle.net/d07f6uvf/