datatables + lengthMenu + All + serverside process

2019-08-11 06:19发布

问题:

This is a basic datatables fiddle. This is the default and the dropdowns will show the follwoing Show options 10, 25, 50, 75 and 100 records:

Now what I would like to get working is the "lengthMenu": [ [10, 25, 50, -1], [10, 25, 50, "All"] ] which I can in this fiddle. But what if I use server side processing, this is where the All option does not work for me. The others do. When I select All it dispalys the data that it was showing and the at the bottom says No data found in the server

As far as i Know the only difference is the data comes from the server. Can anyone advise how i can trouble shoot this? As far as I can tell when I select All I am sending length:-1 and for 10 it is length:10 so not sure why All is not working

        $(document).ready(function() {
            var dataTable = $('#employee-grid').DataTable( {
                "lengthMenu" : [[ 10, 25, 50, -1 ],[ '10', '25', '50', 'All' ]],
                //"pageLength": 25,
                "processing": true,
                "serverSide": true,
                "ajax":{
                    url :"employee-grid-data.php", // json datasource
                    type: "post",  // method  , by default get
                    error: function(){  // error handling
                        $(".employee-grid-error").html("");
                        $("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
                        $("#employee-grid_processing").css("display","none");

                    }
                }                   
            } );
        } );


回答1:

When using server-side processing, you should ignore the start and length request parameters ONLY IF the length parameters is -1 in your PHP script in order to return all records.



回答2:

"lengthMenu": [ [10, 25, 50, -1], [10, 25, 50, "All"] ]

1)Means that "ALL" is assigned the value of -1.

2)that's the reason why when u select All your are sending length:-1 and for 10 it is length:10

3)that's the reason why you also get No data found in the server - error

4)to proper this give this in your Controller

var length = Request.Form.GetValues("length").FirstOrDefault() == "-1" ? Convert.ToString(YOUR_LIST.Count()) : Request.Form.GetValues("length").FirstOrDefault();

5)this will tell if length == -1 then take your list total count so that it displays all rows .