使用Datatables.net数据表时,如何知道在分页控件中单击了哪个页码

时间:2018-10-12 00:27:53

标签: javascript jquery datatables asp.net-core-mvc asp.net-core-webapi

我有一个ASP.Net Core 2.1 API,用作我网站的后端数据存储。返回记录列表的API端点接受PageNumber和PageSize参数,然后返回指定的记录页面。

现在,在我的ASP.Net 2.1 MVC网站上,我试图使用Datatables.net数据表向用户显示记录列表。我一切正常,只是当用户单击分页控件中的页码时,我无法弄清楚如何从数据表中获取页码。在我看过的示例中,Controller具有loaddata操作,它正在从HttpContext.Request.Form检索值,但是我看不到有可用的实际PageNumber属性。

这是我视图中的javascript;

<script>

    jQuery(document).ready(function ($) {

        var table = $("#companylist").DataTable({
            "processing": true,
            "serverSide": true,
            "filter": true,
            "orderMulti": false,
            "ajax": {
                "url": "/Companies/LoadData",
                "type": "POST",
                "datatype": "json"
            },
            "columnDefs": [
                { "orderable": false, "targets": 7 },
                { "className": "text-center", "targets": [6] },
                {
                    "targets": [2],
                    "createdCell": function(td, cellData, rowData, row, col) {
                        if (cellData) {
                            $(td).html('<i class="far fa-check-circle text-primary""></i>');
                        } else {
                            $(td).html('<i class="far fa-times-circle text-danger""></i>');
                        }
                    }
                }
            ],
            "columns": [
                { "data": "Id", "name": "Id", "autoWidth": true },
                { "data": "CompanyName", "name": "CompanyName", "autoWidth": true },
                { "data": "PrimaryContactName", "name": "PrimaryContactName", "autoWidth": true },
                { "data": "PrimaryContactTitle", "name": "PrimaryContactTitle", "autoWidth": true },
                { "data": "PrimaryContactPhone", "name": "PrimaryContactPhone", "autoWidth": true },
                { "data": "PrimaryContactEmail", "name": "PrimaryContactEmail", "autoWidth": true },
                { "data": "IsEnabled", "name": "IsEnabled", "autoWidth": true },
                {
                    "render": function (data, type, full, meta) { return `<a href="/companies/edit?id=${full.Id}"><i class="far fa-edit text-primary" title="Edit"></a>`; }
                }
            ],
            // From StackOverflow http://stackoverflow.com/a/33377633/1988326 - hides pagination if only 1 page
            "preDrawCallback": function (settings) {
                var api = new $.fn.dataTable.Api(settings);
                var pagination = $(this)
                    .closest('.dataTables_wrapper')
                    .find('.dataTables_paginate');
                pagination.toggle(api.page.info().pages > 1);
            }

        });

    });

这是我的LoadData控制器动作;

    public async Task<IActionResult> LoadData()
    {
        try
        {
            await SetCurrentUser();
            ViewData["Role"] = _currentRole;


            var draw = HttpContext.Request.Form["draw"].FirstOrDefault();
            var start = Request.Form["start"].FirstOrDefault();
            var length = Request.Form["length"].FirstOrDefault();
            var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
            var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();
            var searchValue = Request.Form["search[value]"].FirstOrDefault();
            var pageSize = length != null ? Convert.ToInt32(length) : 0;

            var request = new CompaniesGetListRequest
            {
                OrderBy = SetOrderBy(sortColumn, sortColumnDirection),
                Filter = SetFilter(searchValue),
                PageNumber = ???, //<--- Where do I get tis value?
                PageSize = pageSize,

            };

            var tokenSource = new CancellationTokenSource();
            var token = tokenSource.Token;

            var companyData = await _client.GetCompanyListAsync(request, "api/companies/filtered", token);

            var recordsTotal = companyData.Paging.TotalCount;
            var data = companyData.Companies.ToList();
            return Json(new
            {
                draw = draw,
                recordsFiltered = companyData.Paging.TotalCount,
                recordsTotal = companyData.Paging.TotalCount,
                data = companyData.Companies.ToList()
            });

        }
        catch (Exception ex)
        {
            const string message = "An exception has occurred trying to get the list of Company records.";
            _logger.LogError(ex, message);
            throw;
        }
    }

看起来我只有“开始”值,它是列表中的下一个记录号,而长度是页面大小。我需要确定PageNumber,因为由于数据集的大小,我不想从后端数据存储中返回整个数据集。我只想一次抓一页。

这可能是一个简单的问题,但我没有运气找到答案。

1 个答案:

答案 0 :(得分:1)

我从Datatables论坛获得了这个答案。

var page = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1;

希望这会有所帮助。

PS:Link to Forum