小编典典

加载ASP.Net MVC JSONResult jQuery DataTables

json

我正在尝试使DataTables(http://datatables.net)与ASP.Net MVC控制器返回的JsonResult一起使用。我不断收到“
DataTables警告(表ID =’示例’):行0的数据源请求的未知参数‘0’”错误,根据文档表示无法找到这些列。

控制器中返回JsonResult的代码如下:

    public JsonResult LoadPhoneNumbers()
    {
        List<PhoneNumber> phoneNumbers = new List<PhoneNumber>();
        PhoneNumber num1 = new PhoneNumber { Number = "555 123 4567", Description = "George" };
        PhoneNumber num2 = new PhoneNumber { Number = "555 765 4321", Description = "Kevin" };
        PhoneNumber num3 = new PhoneNumber { Number = "555 555 4781", Description = "Sam" };

        phoneNumbers.Add(num1);
        phoneNumbers.Add(num2);
        phoneNumbers.Add(num3);

        return Json(phoneNumbers, JsonRequestBehavior.AllowGet);
    }

PhoneNumber只是一个普通的C#类,具有2个属性,即Number和Description。

检索和加载数据的javascript如下所示:

<script>
$(document).ready(function () {
    $('#example').dataTable({
        "bProcessing": true,
        "sAjaxSource": '/Account/LoadPhoneNumbers/',
        "sAjaxDataProp": ""
    });
});
</script>

和html看起来像:

<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
<thead>
    <tr>
        <th>
            Number
        </th>
        <th>
            Description
        </th>
    </tr>
</thead>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>

我已将sAjaxDataProp设置为空字符串,以便DataTables不会查找aaData。即使当我在控制器中像这样显式设置aaData时:

return Json(new { aaData = phoneNumbers });

我仍然收到错误。有什么建议吗?

谢谢!


阅读 226

收藏
2020-07-27

共1个答案

小编典典

以下对我有用:

$(function () {
    $('#example').dataTable({
        bProcessing: true,
        sAjaxSource: '@Url.Action("LoadPhoneNumbers", "Home")'
    });
});

我已删除该sAjaxDataProp财产。

使用此数据源:

public ActionResult LoadPhoneNumbers()
{
    return Json(new
    {
        aaData = new[] 
        {
            new [] { "Trident", "Internet Explorer 4.0", "Win 95+", "4", "X" },
            new [] { "Gecko", "Firefox 1.5", "Win 98+ / OSX.2+", "1.8", "A" },
            new [] { "Webkit", "iPod Touch / iPhone", "iPod", "420.1", "A" }
        }
    }, JsonRequestBehavior.AllowGet);
}

对于您的手机示例:

public ActionResult LoadPhoneNumbers()
{
    var phoneNumbers = new List<PhoneNumber>(new[] 
    {
        new PhoneNumber { Number = "555 123 4567", Description = "George" },
        new PhoneNumber { Number = "555 765 4321", Description = "Kevin" },
        new PhoneNumber { Number = "555 555 4781", Description = "Sam" }
    });

    return Json(new
    {
        aaData = phoneNumbers.Select(x => new[] { x.Number, x.Description })
    }, JsonRequestBehavior.AllowGet);
}
2020-07-27