使用Jquery.DataTable将Json绑定到table

首先,新建一个edmx绑定数据库中的表。

JsonController.cs

    public class JsonController : Controller
    {
        // GET: Json
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult AjaxMethod()
        {
            TestEntities entities = new TestEntities();
            List<Animal> customers = (from animal in entities.Animals
                                        select animal).ToList();
            return Json(customers);
        }
    }

Index.cshtml

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    <div style="width: 500px">
        <table id="tblCustomers" cellpadding="0" cellspacing="0" border="1" style="border-collapse:collapse">
            <thead>
                <tr>
                    <th>Species</th>
                    <th>Weight</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
    <link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        $(function () {
            $.ajax({
                type: "POST",
                url: "/Json/AjaxMethod",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                },
                error: function (response) {
                    alert(response.d);
                }
            });
        });
        function OnSuccess(response) {
            $("#tblCustomers").DataTable(
                {
                    bLengthChange: true,
                    lengthMenu: [[5, 10, -1], [5, 10, "All"]],
                    bFilter: true,
                    bSort: true,
                    bPaginate: true,
                    data: response,
                    columns: [
                        { 'data': 'species' },
                        { 'data': 'weight' }
                    ]
                });
        };
    </script>
</body>
</html>

结果演示:

posted @ 2020-07-09 17:36  Kyle0418  阅读(1041)  评论(0编辑  收藏  举报