Example of Ajax data loaded via .net WebMetho
Example of Ajax data loaded via .net WebMetho

Hi there,
Are any of you aware of a good example of how to use a c# web method to load data into a DataTables table via an Ajax call?
Specifically I'm interesting in see the syntax used in "ajax:" callback function and how the .net WebMethod itself is set up to return a Json response.
Or asking the same question in a slightly different way ... does anyone fancy completing the missing sections in the template below?
Many thanks,
John
>
Filename: GetTableData.aspx
<!DOCTYPE html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<html>
<head>
<!-- Sever Side scripting -->
<script runat="server">
[WebMethod]
public static string GetTableData()
{
string strJson;
/*
get data, format data, return formatted data
could return a hand crafted string for now, just to test.
*/
return strJson;
}
</script>
</head>
<body>
<h2>Load data table with objects.</h2>
<table id="example">
<thead>
<tr>
<th>FirstColumn</th>
<th>SecondColumn</th>
</tr>
</thead>
</table>
<!-- Client side scripting: script libraries for jQuery and DataTables -->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$('#example').DataTable( {
ajax: {
url: "GetTableData.aspx/GetTableData",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
},
columns: [
{ data: "FirstColumn" },
{ data: "SecondColumn" }
]
} );
</script>
</body>
</html>
This discussion has been closed.
Answers
It is probably poor form to answer one's own question, so I apologise for that. But having spent a fair while "failing" I have now managed to load my table successfully via AJAX and thought it might help others to see the whole example. I'm aware that I am by no means an expert so whilst I am sure the code below works, I'm also sure there are better ways of doing things, so feel free to offer improvements.
To keep it simple I have put both the server side processing (the c# bit) and the client side JavaScript in the same file, obviously you could separate them out if you wanted.
GetTableData.aspx
No - its great that you posted back with the solution you found - thanks!
The one thing I would suggest is not attempting to build the JSON yourself though - use a library such as JSON.NET to create the JSON for you from an object. Then you don't need to worry about commas, quoting and the rest of it.
Allan