c# - ASP.NET MVC & Ajax json Datatables 错误 - json 错误,单元格不显示数据
问题描述
这可能是重复的,但我已经尝试了在堆栈交换和 datatables.net 论坛上可以找到的所有内容。我根本无法让它工作。
我有var listOfFiles
以下模型(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; }
}
控制器:
[HttpGet]
public ActionResult GetAudio()
{
var listOfFiles = asa.GetAudioFilesFromServer(serverpath);
return Json(new { data = listOfFiles }, JsonRequestBehavior.AllowGet);
}
来自 chrome 的控制台输出 -
看法 -
<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" }
]
}
});
});
使用上面的代码,我得到 DataTables 错误 1。
我试过 了jsonData.responseJSON
序列化 json 时出现 DataTables 错误 4,但我知道使用上面的代码我需要一个 json 数组,而不是字符串。
我已经密切关注这两个错误的故障排除。我的 json 看起来很完美,有人能指出我正确的方向吗?我无法弄清楚我做错了什么!
提前致谢。
解决方案
您可以在 init DataTable 中移动 AJAX 调用,如下所示
$(document).ready(function () {
$('#audiotable').DataTable({
"ajax": "/Music/GetAudio",
"columns": [
{ "data": "Title" },
{ "data": "Artist" },
{ "data": "Album" },
{ "data": "Duration" }
]
});
});
推荐阅读
- vb.net - 无法使用 linq 增加计数器
- android - android Kotlin 中带有 JSON 的 GraphQL 突变
- flutter - 状态不变(停留在初始状态)
- python - Pandas 检查给定列表中是否存在单元格中的单词(在许多单词中)
- react-native - React Native Pod 错误 - [!] 无效的 `Podfile` 文件:767:'' 处的意外令牌。| 相关问题 #448
- javascript - 将数组索引处的值更改为 falsey 会使数组稀疏吗?
- typescript - 泛型类型的 TypeScript 部分
- r - 在闪亮的服务器上找不到返回的 rmarkdown
- python - 如何检查对象是否为 np.array()?
- angular - 如何使用 php 后端更新 Angular Reactive 表单