skip to Main Content

I am using jQuery DataTables to display data in ASP.NET Core 6 MVC project. I want to display a custom message when no data was returned from the SQL query, instead of the default text, "Showing 0 to 0 of 0 entries". I tried a couple of methods as shown here.

Method 1, using the language option:

var dataTableOptions = {
   "paging": true,
   "lengthChange": false,
   "searching": true,
   "ordering": true,
   "info": true,
   "autoWidth": false,
   "responsive": true,
   "columnDefs": "",
   "processing": true,
   "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
   "pageLength": 10,
   "language": {
       "emptyTable": 'No records found!',
       "zeroRecords": 'No records found!'
   },
   //More config code here
}

Method 2 displaying the message as a text of a div:

<div id="emptyRows">No records found!</div>

var myDataTable = $('#riskReport').DataTable(dataTableOptions);
if (!myDataTable.data().any()) {
    //alert('No records found!');  //This works     
    //$('#riskReport_info').text('No records found!'); //This didn't work
    $('#emptyRows').show();
}            
else {      
    $('#emptyRows').hide(); //Code never reached here
}

The second method displays the ‘No records found!’ as the text of the div, when no data was returned by the SQL. However when the search method was changed such that data was returned successfully, still the ‘No records found!’ is displayed since the div is not hidden. As an additional option, I tried to set the text of #riskReport_info, which is the id used by the DataTable natively to display the default message.

2

Answers


  1. Try doing something like the following to replace the if statement in "method 2":

    if (myDataTable.table.rows()[0].length === 0) {
    // ...
    }
    

    Only for the initial check. You’ll need to add code to do the same check every time the table may be updated, such as when you perform a search. As such, this logic would probably be better suited as a function.

    Login or Signup to reply.
  2. For Method 1, ensure emptyTable and zeroRecords are correctly set and that no server-side processing is interfering.

    For Method 2, bind the draw event to show or hide the message after each table update:

    myDataTable.on('draw', function () {
        if (!myDataTable.data().any()) {
            $('#emptyRows').show();
        } else {
            $('#emptyRows').hide();
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search