Click here to Skip to main content
13,863,336 members
Rate this:
 
Please Sign up or sign in to vote.
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 4:34am

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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:
"ajax": {
    ...
    dataFilter: function (res) {
        var parsed = JSON.parse(res);
        return { data: parsed.d };
    }
},
   
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web01 | 2.8.190214.1 | Last Updated 12 Feb 2019
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100