Search code examples
javascriptc#asp.net-mvcdatatablespagination

How to pass pagination parameters from datatables.net


I am using datatables.net in C# MVC. I am doing server-side loading and trying to do pagination but I don't understand how to pass parameters like skiprecords, totalrecords to my controller from Javascript/Ajax.

Right now I am passing no parameter and datatable is loading fine but I want to do server-side pagination. I can handle controller-side code which is not an issue. The issue is to pass parameters so my controller knows it is on page 4 and only shows those records.

The example given below on their website is working but they are not passing any parameter and somehow server-side pagination is working. No idea how.

https://datatables.net/examples/data_sources/server_side

Here's my JS code:

dataTable = $("#tblDetails").DataTable(
    {
        "sAjaxSource": "/MyController/MyMethod",
        "bServerSide": true,
        "bProcessing": true,
        "bSearchable": true,
        "order": [[1, 'asc']],
        "columns": [
            {
                "data": "Col1",
                "autoWidth": true,
                "searchable": true
            },
            {
                "data": "Col2",
                "autoWidth": true,
                "searchable": true
            },
        ]
    }
);

What parameters to be passed for pagination?


Solution

  • From the Server-side processing docs, it will provide the start and length as query string parameters to your API.

    In your API, you get the parameters and perform pagination with Skip() and Limit() from the LINQ query.

    public JsonResult MyMethod(int draw = 1, int start = 0, int length = 10)
    {
        int recordsTotal = /* Dataset instance */.Count();
    
        var filteredData = /* Dataset instance */
            .Skip(start)
            .Limit(length)
            .ToList();
    
        draw++;
    
        return Json(new 
        { 
            draw = draw, 
            recordsFiltered = filteredData.Count(), 
            recordsTotal = recordsTotal, 
            data = filteredData 
        });
    }