数据表的 Razor Pages return Json

Razor Pages return Json for DataTables

我有一个 razor 项目,我在其中实现了数据表。我正在尝试以这种方式使用 ajax 从数据库中动态检索数据:

$('#orariDipendenti').DataTable({
            'orderMulti': false,
            'stateSave': true,
            'paging': true,
            'pageLength': 10,
            'filter': false,
            'processing': true,
            'serverSide': true,
            'ajax': {
                url: '?handler=LoadData',
                type: 'POST',
                dataType: 'json',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
            },
        });

我的后台代码是这样的:

public JsonResult LoadTable()
    {
        try
        {
            var idDipendente = HttpContext.Session.GetInt32("IdDipendente");

            var draw = HttpContext.Request.Form["draw"].FirstOrDefault();

            var length = Request.Form["length"].FirstOrDefault();

            var start = Request.Form["start"].FirstOrDefault();

            int pagesize = length != null ? Convert.ToInt32(length) : 0;

            int skip = start != null ? Convert.ToInt32(start) : 0;

            int recordstotal = 0;

            var recordData = context.Pres_Orari.Where(x => x.IdDipendente == idDipendente).ToList();

            recordstotal = recordData.Count;

            var data = recordData.Skip(skip).Take(pagesize).ToList();

            return new JsonResult(new { draw = draw, recordsFiltered = recordstotal, recordsTotal = recordstotal, data = data });
        }
        catch (Exception)
        {
            throw;
        }
    }

打开页面时出现的错误是这样的:

DataTables warning: table id={id} - Invalid JSON response.

我知道返回的 json 有问题,但我不知道出在哪里。有人可以帮助我吗?

首先,您的处理程序名称是 LoadTable,您在 ajax 中的 url 是 url: '?handler=LoadData'。您需要更改 url 到 url: '?handler=LoadTable'。这是一个工作演示(我也将 xhr.setRequestHeader("XSRF-TOKEN" 更改为 xhr.setRequestHeader("RequestVerificationToken",如果你的代码可以工作,你不需要更改 xhr.setRequestHeader("XSRF-TOKEN"):

cshtml:

@Html.AntiForgeryToken()
    <table id="orariDipendenti" class="table table-striped table-bordered" style="width:100%">
        <thead class="thead-dark">
            <tr class="table-info">
                <th>IdDipendente</th>
                <th>Name</th>
               
            </tr>
        </thead>
    </table>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
    
        <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
        <script>
    <script>
            $(function () {
                $('#orariDipendenti').DataTable({
                    'orderMulti': false,
                    'stateSave': true,
                    'paging': true,
                    'pageLength': 10,
                    'filter': false,
                    'processing': true,
                    'serverSide': true,
    
                    ajax: {
                        url: '?handler=LoadTable',
                        type: 'POST',
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("RequestVerificationToken",
                                $('input:hidden[name="__RequestVerificationToken"]').val());
                        },
                    },
                    columns: [
                        { data: 'idDipendente' },
                        { data: 'name' },
                    ]
                });
            });
           
    
        </script>

型号:

 public class MyModel1 {
        public int IdDipendente { get; set; }
        public string Name { get; set; }

    }

cshtml.cs(我用假数据测试):

public static List<MyModel1> list = new List<MyModel1> { new MyModel1 { IdDipendente = 1, Name = "name1" }, new MyModel1 { IdDipendente = 2, Name = "name2" }, new MyModel1 { IdDipendente = 3, Name = "name3" } };
public JsonResult OnPostLoadTable()
        {
            try
            {
                var idDipendente = 1;

                var draw = HttpContext.Request.Form["draw"].FirstOrDefault();

                var length = Request.Form["length"].FirstOrDefault();

                var start = Request.Form["start"].FirstOrDefault();

                int pagesize = length != null ? Convert.ToInt32(length) : 0;

                int skip = start != null ? Convert.ToInt32(start) : 0;

                int recordstotal = 0;

                var recordData = list.Where(x => x.IdDipendente==idDipendente).ToList();

                recordstotal = recordData.Count;

                var data = recordData.Skip(skip).Take(pagesize).ToList();

                return new JsonResult(new { draw = draw, recordsFiltered = recordstotal, recordsTotal = recordstotal, data = data });
            }
            catch (Exception)
            {
                throw;
            }
            
            
        }
    }

结果: