Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am using datatables.net plug in to load data in table.
I called web method in asp.net page and return 
JsonConvert.SerializeObject(result) 
as string; 
I could see below json string as response but I do not know how to bind them with datatables.net

{"d":"[{\"Apple\":507,\"Orange\":6,\"Mango\":75,\"Peach\":638,\"City\":\"SAN ANTONIO\",\"State\":\"TX\"},{\"Apple\":507,\"Orange\":6,\"Mango\":75,\"Peach\":638,\"City\":\"SAN ANTONIO\",\"State\":\"TX\"}]"}


What I have tried:

I tried to
JsonConvert.SerializeObject(new {data =result})
Posted
Updated 12-Feb-19 3:34am

1 solution

DataTables expects the returned value to be an object with a property called data which contains the list of data to display:
ajax | Options | DataTables.net[^]

An ASP.NET WebMethod always wraps the returned object in an object with a property called d, to try to avoid a potential CSRF issue if the result is an array:
Anatomy of a Subtle JSON Vulnerability | You’ve Been Haacked[^]

You've also double-encoded the result - your web method should just return the data directly, rather than JSON-encoding it.

Once you've changed your web method to remove the extra JSON encoding, you can use the dataFilter option in your script to modify the returned data to match the expected format. For example:
JavaScript
"ajax": {
    ...
    dataFilter: function (res) {
        var parsed = JSON.parse(res);
        return { data: parsed.d };
    }
},
 
Share this answer
 
Comments
istudent 12-Feb-19 9:50am    
When I did that I got some Row_ID error. I can't post what the exact error was right now. But it was something about row id
Richard Deeming 12-Feb-19 9:53am    
Without the exact error message, there's no way to tell you what the problem is.

Let me know once you've got the exact error message.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900