加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

加载ASP.Net MVC JSONResult jQuery DataTables

发布时间:2020-12-15 20:14:24 所属栏目:asp.Net 来源:网络整理
导读:我试图让DataTables(http://datatables.net)使用ASP.Net MVC控制器返回的JsonResult.我继续收到一个“DataTables警告(表id =’example’):从数据源为第0行请求的未知参数’0’错误,根据文档意味着它找不到列. 返回JsonResult的控制器中的代码如下所示: pub
我试图让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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读