DataTables未定义的“长度”属性

时间:2018-07-12 09:18:35

标签: c# asp.net-mvc datatables

我在MVC项目中使用DataTables,但是当我返回“未捕获的TypeError:无法读取未定义的属性'length'”错误。

我的js代码:

$('.datatable-responsive-column-controlled').DataTable({
   processing: true,
   serverSide: true,
   ajax: {
        url: "@Html.Raw(Url.Action("List", "Prices"))",
        type: "POST"
    },
    columns: [
        { "data": "Id" },
        { "data": "Name" },
        { "data": "Price" },
    ],
    ordering: false,
    responsive: {
        details: {
            type: 'column'
        }
    },
    columnDefs: [
        {
            className: 'control',
            orderable: false,
            targets: 0
        },
        {
            width: "100px",
            targets: [3]
        },
        {
            orderable: false,
            targets: [3]
        }
    ]
});

这是我的json结果:

{"ExtraData":null,"Data":[{"Name":"Apple","Price":"TRY 15.50","Id":1}],"Errors":null,"Total":1,"iTotalRecords":1,"iTotalDisplayRecords":1}

PS:我已经搜索了现有问题,但没有任何解决方案能够解决我的问题。因此,我问了一个新问题。

1 个答案:

答案 0 :(得分:1)

根据文档(请参阅参考部分),DataTable期望来自AJAX调用的JsonResult操作方法的JSON响应,其中包含以下结构之一:

1)简单的数据数组

// JSON
[{ "Name":"Apple",
   "Price":"TRY 15.50",
   "Id":1 }]

// DataTable
$('#table').DataTable({
    ajax: {
        url: '@Url.Action("ActionName", "ControllerName")',
        dataSrc: ''
    },
    // column definition
});

2)具有data属性的对象

// JSON
"data": [{ "Name":"Apple",
          "Price":"TRY 15.50",
          "Id":1 }]

// DataTable
$('#table').DataTable({
    ajax: {
        url: '@Url.Action("ActionName", "ControllerName")',
        dataSrc: 'data'
    },
    // column definition
});

由于传递的JSON对象中的data属性名为Data(请注意,大写字母会有所不同,因为JS具有区分大小写的规则),因此应使用ajax.dataSrc选项进行设置数据属性名称:

$('.datatable-responsive-column-controlled').DataTable({
   processing: true,
   serverSide: true,
   ajax: {
        url: "@Url.Action("List", "Prices")",
        type: "POST",
        dataSrc: "Data" // add this line
    },
    columns: [
        { "data": "Id" },
        { "data": "Name" },
        { "data": "Price" },
    ],

    // other stuff
});

参考文献:

DataTables Manual - AJAX Data array location

DataTables: Common JS Console Errors