I have read the datatables.net documentation on populating a datatable using ajax and can’t get anywhere.
FROM THE CONTROLLER USING ASP.NET Core, the following method:
[HttpGet ("EmployeesJSON")]
public JsonResult EmployeesJSON()
{
var AllEmployees = _iEmployeeService.GetAllEmployees();
var json = JsonConvert.SerializeObject(AllEmployees, Formatting.Indented);
return new JsonResult(json);
}
Result returned from controller:
FROM Javascript using AJAX
var _data;
$(document).ready(function () {
$.ajax({
type: $(this).attr('GET'),
url: "Employees/EmployeesJSON",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) { // on success..
_data = response;
initDataTable(); //initialize the data table
}
});
});
What data looks like from AJAX call
initDataTable() is called if success from AJAX Call
function initDataTable() {
var employeeTable = $('#employee_table').DataTable(
{
scrollX: true,
scrollY: 400,
data: _data,
columns: [
{ sName: "LastName", data: "LastName", bSearchable: true, bSortable: false }
],
lengthMenu: [[25, 50, -1], [25, 50, 'All']],
});
}
Error message from datatables.net
3
Answers
I'm placing this here in case someone else runs into this.
I was referencing a column with the wrong field name. Make sure your column names match! Final AJAX and datatable init:
you have to put the names in quotes
if you still have some problems, you can try a camel case
Here is a demo using the suggestions I made in my comments:
It assumes your Ajax call returns JSON like the following:
Notes:
My sample JSON only contains 5 fields per record – your JSON contains more, of course.
My DataTable only uses 2 of my 5 fields – but you can extend my code to add more fields, as needed. See the
columns:
section of the code.I have used the DataTables built-in support for Ajax (it makes the code simpler, in my opinion, but you can still use an external Ajax call if you prefer).
Because your JSON uses an unnamed array (according to the screenshot in your question), you need to use
dataSrc: ''
. This tells DataTables where the array can be found in your JSON.In contrast, if you had JSON that looked like this (just as an example):
…then you would need to use
dataSrc: 'foo'
because that is where the array of objects is located in the JSONsName
andbSearchable
, I use the modern versionsname
,searchable
and so on. The older names still work.