Reputation: 103
This may be a duplicate but I've tried everything I can find on stack exchange and datatables.net forums. I can't get it to work at all.
I have var listOfFiles
which is a list of the following model (List<AudioModel>
):
public class AudioModel
{
public int Id { get; set; }
public string Title { get; set; }
public string Artist { get; set; }
public string Album { get; set; }
public string Duration { get; set; }
public bool Select { get; set; }
public string FilePath { get; set; }
}
Controller:
[HttpGet]
public ActionResult GetAudio()
{
var listOfFiles = asa.GetAudioFilesFromServer(serverpath);
return Json(new { data = listOfFiles }, JsonRequestBehavior.AllowGet);
}
Console output from chrome -
View -
<table class="display compact table table-striped table-hover table-condensed" id="audiotable">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Artist</th>
<th>Album</th>
<th>Duration</th>
<th>Select</th>
<th>FilePath</th>
</tr>
</thead>
</table>
$(document).ready(function () {
var jsonData = $.ajax({
type: "GET",
contentType: "json",
url: "@Url.Action("GetAudio", "Music")"
})
// screenshot of this above
console.log(jsonData);
$("#audiotable").DataTable({
"ajax": {
"type": "GET",
"contentType": "json",
"data": jsonData,
"columns": [
{ "data": "Id" },
{ "data": "Title" },
{ "data": "Artist" },
{ "data": "Album" },
{ "data": "Duration" },
{ "data": "Select" },
{ "data": "FilePath" }
]
}
});
});
with the above code I get DataTables error 1.
I've tried
jsonData.responseJSON
I get DataTables error 4 when I serialize json but I understand that with the above code I need a json array, not a string.
I've closely followed the troubleshooting for both errors. my json looks perfect, is anyone able to point me in the right direction? I can't figure out what I'm doing wrong!
Thanks in advance.
Upvotes: 0
Views: 155
Reputation: 3625
What you are doing is getting your jsondata using ajax then passing the data to ajax call of datatables init. That's not going to work. You don't need your ajax call outside of datatables.
Try this:
$("#audiotable").DataTable({
"ajax": {
url: "@Url.Action("GetAudio", "Music")"
type: "GET"
},
"columns": [
{ "data": "Id" },
{ "data": "Title" },
{ "data": "Artist" },
{ "data": "Album" },
{ "data": "Duration" },
{ "data": "Select" },
{ "data": "FilePath" }
]
});
Update your action to this:
[HttpGet]
public ActionResult GetAudio()
{
var listOfFiles = asa.GetAudioFilesFromServer(serverpath);
return Json(listOfFiles, JsonRequestBehavior.AllowGet);
}
Upvotes: 0
Reputation: 18973
You can move AJAX call inside init DataTable like below
$(document).ready(function () {
$('#audiotable').DataTable({
"ajax": "/Music/GetAudio",
"columns": [
{ "data": "Title" },
{ "data": "Artist" },
{ "data": "Album" },
{ "data": "Duration" }
]
});
});
Upvotes: 0