加载ASP.Net MVC JSONResult jQuery DataTables

前端之家收集整理的这篇文章主要介绍了加载ASP.Net MVC JSONResult jQuery DataTables前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图让DataTables(http://datatables.net)使用ASP.Net MVC控制器返回的JsonResult.我继续收到一个“DataTables警告(表id =’example’):从数据源为第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 });

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

谢谢!

解决方法

以下作品对我来说非常棒:
$(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);
}
原文链接:https://www.f2er.com/aspnet/246143.html

猜你在找的asp.Net相关文章