0

I'm using datatable.js, I have table in view and API returns JSON results. I have lots of rows and i want to bind them by each page.Is there any way that datatable do it for me? I read lots of documentation but I didn't find anything useful for API

API Controller

 public IHttpActionResult Get(int id)
    {
     return Ok(_context.Students.OrderBy(c => c.id).Skip((id - 1) * 10).Take(10).ToList());

    }

Here is my table config

    <script>$(document).ready(function () {
var pageindex = 1;

var table = $("#staff").DataTable({
                "processing": true,
                "serverSide": true,
    ajax: {
        url: "/Api/staffs",
        dataSrc: "",
        data: {
            id: pageindex,
           },
            },
            columns: [
                {
                    data: "stf_FirstName",
                },
                {
                    data: "stf_LastName",
                },
                {
                    data: "stf_Code",

                }
            ]
});

table.on('page', function () {
    Currentpagenum();
});
function Currentpagenum() {
    var info = table.page.info();
    pageindex = (info.page + 1);
}
    });</script>

1 Answer 1

2

If there are lots of rows than server side processing should be used

Try this :

HTML :

<table id="tblGrid" class="table display nowrap" style="width:100%">            
</table>

JS :

function SetGrid() {
    $('#tblGrid').DataTable({
        "proccessing": true,
        "serverSide": true,
        // server side
        "ajax": {
            url: "/api/YourController/Method",
            type: 'POST',
            "data": {
                Param1: Value1
            }
        },
        // if client side
        //data: YourList,   // Js Array     
        columns: [
            { data: 'Id' },                
            { data: 'Name', title: "Name" },
            ...
            ...
            { title: "Actions"},
        ],
        "columnDefs": [
            { targets: 0, visible: false,},                
        ],        
        "ordering": false,
        "lengthChange": false,
        "pageLength": 10,
        "bDestroy": true,
        "oLanguage": {
            "sEmptyTable": "No Record Found"
        },        
    });

}

Sample C# :

public object YourMethod(Param1 Value1)
{
    var start = int.Parse(HttpContext.Current.Request.Form["start"]);

    var result = new {
        draw = HttpContext.Current.Request.Form["draw"],
        recordsTotal = YourList.Count,
        recordsFiltered = YourList.Count,
        data = YourList.Skip(start).Take(10).ToList()
    };

    return result;   
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.