MVC Core 2.2 Ajax source ... won't work!
MVC Core 2.2 Ajax source ... won't work!

Hi, I can't seem to get my ajax-sourced datatable to work. It appears that datatables.net cannot resolve the returned Json data.
Also, assuming the table loaded, I need to be able to refresh the table from a new call to a controller method that returns the source data (like GetCaseNotes() below). I don't know how to refresh the table without reloading the whole page, which is what I'm trying to avoid. For example, if a new note is added to the table via a client-side form, I'd like to store the note in the database, then refresh the table with new data.
Error Message: "datatables.min.js:76 Uncaught TypeError: Cannot read property 'length' of undefined"
Controller:
public class CaseNoteItem
{
public string NoteId { get; set; }
public string CaseId { get; set; }
public string Date { get; set; }
public string Note { get; set; }
}
[HttpGet]
public IActionResult GetCaseNotes([FromForm] int caseId)
{
// DUMMY DATA FOR TEST //
List<CaseNoteItem> Data = new List<CaseNoteItem>();
Data.Add(new CaseNoteItem
{
NoteId = "3",
CaseId = "11",
Date = DateTime.Today.ToShortDateString(),
Note = "Ajax Note 01"
});
Data.Add(new CaseNoteItem
{
NoteId = "4",
CaseId = "11",
Date = DateTime.Today.ToShortDateString(),
Note = "Ajax Note 02"
});
var data = Json(Data);
return data;
}
View
<table id="NotesListTable" class="table table-sm table-striped table-bordered nowrap compact" style="width: 100%;">
<thead>
<tr>
<th>Note ID</th>
<th>Case ID</th>
<th class="text-center">Date</th>
<th class="px-2">Note</th>
</tr>
</thead>
<tfoot></tfoot>
</table>
JavaScript (in .ready())
$('#NotesListTable').DataTable({
ajax: {
url: '@Url.Action("GetCaseNotes", "Case")',
columns: [
{ data: "NoteId" },
{ data: "CaseId" },
{ data: "Date" },
{ data: "Note" }
]
}
});
Json Response
The controller method gets hit and debug tools show the following response from the request:
[{"noteId":"3","caseId":"11","date":"10/16/2019","note":"Ajax Note 01"},{"noteId":"4","caseId":"11","date":"10/16/2019","note":"Ajax Note 02"}]
Thanks! I've spent over a day on this....
Brian
This question has an accepted answers - jump to answer
Answers
Hi Brian,
Two things:
columns
array needs to be at the top level of the DataTables configuration object (interestingly, that's the second time in two days we've seen this issue -- were you following a blog post or exercise somewhere?).ajax.dataSrc
to tell DataTables just to expect a plain array of data:Allan
allan ... thank you! Fixed!
I also found how to reload the table via an event method (client side) ... is this the best way?:
Brian