首页 > 解决方案 > 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 看起来很完美,有人能指出我正确的方向吗?我无法弄清楚我做错了什么!

提前致谢。

标签: c#jsonajaxasp.net-mvcdatatables

解决方案


您可以在 init DataTable 中移动 AJAX 调用,如下所示

$(document).ready(function () {
            $('#audiotable').DataTable({
                "ajax": "/Music/GetAudio",
                "columns": [
                    { "data": "Title" },
                    { "data": "Artist" },
                    { "data": "Album" },
                    { "data": "Duration" }
                ]
            });
    });

推荐阅读