Search code examples
jqueryajaxdatatablesasp.net-core-mvc

How to select rows from jQuery datatable that uses AJAX call


I am working on a C# ASP.NET Core MVC app and I use jQuery datatable to display data from a database. The problem is I am not able to select single or multiple rows in this table.

I have a table like this in my .cshtml:

<table class="table display table-bordered" id="DATATABLE">
</table>

This is in the script tag:

$("#DATATABLE").DataTable({
    serverSide: true,
    filter: true,
    searchDelay: 1000,
    scrollY: StaticData.TABLE_HEIGHT + 'px',
    lengthMenu: StaticData.TABLE_PAGE_SIZE,
    language: { searchPlaceholder: "Name, Teacher" },
    scrollCollapse: true,
    ajax: {
        url: '/STUD_MANAGEMENT/LoadStud',
        type: 'GET',
        datatype: 'json',
        headers: { 'RequestVerificationToken': 'your json token' },
        data: (d) => {                    
            return { draw: d.draw, start: d.start, length: d.length, search: d.search.value, FilterByColumn: d.columns[d.order[0].column].data, ASC_DSEC: d.order[0].dir }
        },
        beforeSend: () => { ShowLoader(); },
        complete: () => { HideLoader(); },
        dataSrc: (json) => {
            json = json.data;                    
            return json;
        }
    },
    columnDefs: [{ className: "dt-center", targets: [5, 6, 7, 8, 11], width: '2%', }],
    columns: [
        { data: 'STUD_ID', title: 'STUD ID', autoWidth: false, visible: false },
        { data: 'CLASS_ID', title: 'CLASS ID', autoWidth: false, visible: false },
        { data: 'NAME', title: 'Name', autoWidth: true, searchable: true },
        { data: 'AGE', title: 'Age', autoWidth: true },
        { data: 'TEACHER', title: 'Teacher', autoWidth: true },               
    ]            
 });

And the LoadStud() method in the STUD_MANAGEMENT controller is shown here:

public IActionResult LoadStud(int draw = 1, int start = 0, int length = 10, 
                              string search = "", string FilterByColumn = "", string ASC_DSEC = "")
{
    List<STUD_MANAGEMENT> ListData = new List<STUD_MANAGEMENT>();

    int recordsTotal = 0;            

    STUD_MANAGEMENT dm = new STUD_MANAGEMENT();
    dm.STUD_ID = 1;
    dm.CLASS_ID = 1;
    dm.NAME = "James";
    dm.TEACHER = "SEPHORA";
    dm.AGE = "12";

    STUD_MANAGEMENT dm1 = new STUD_MANAGEMENT();
    dm1.STUD_ID = 2;
    dm1.CLASS_ID = 2;
    dm1.NAME = "Naneem";
    dm1.TEACHER = "Chithra";
    dm1.AGE = "15";

    STUD_MANAGEMENT dm11 = new STUD_MANAGEMENT();
    dm11.STUD_ID = 3;
    dm11.CLASS_ID = 3;
    dm11.NAME = "Sony";
    dm11.TEACHER = "Mano USA";
    dm11.AGE = "3";            

    ListData.Add(dm);
    ListData.Add(dm1);
    ListData.Add(dm11);

    recordsTotal = ListData.Count();                    

    var jsonData = new { draw = draw, 
                         recordsFiltered = recordsTotal, 
                         recordsTotal = recordsTotal, 
                         data = ListData };
    return Ok(jsonData);
}

This is the STUD_MANAGEMENT class:

public class STUD_MANAGEMENT
{             
    public int STUD_ID { get; set; }
    public int CLASS_ID { get; set; }      
    public string NAME { get; set; }
    public int AGE { get; set; }   
    public string TEACHER { get; set; }
} 

I want to select single/multiple row in this datatable and suppose that there is a button near by this datatable and onclick() of that button should return the selected row (s) of this datatable.


Solution

  • I want to select single/multiple row in this datatable and suppose that there is a button near by this datatable and onclick() of that button should return the selected row (s) of this datatable.

    You should configure multi-row selection support using select: { style: 'multi' }.

    var table = $('#DATATABLE').DataTable({
                    select: {
                        style: 'multi' // support multi-row selection
                    },
                    ...
                });
    

    Then, you can add a button under the table:

    <button id="getSelectedRows">getSelectedRows</button>
    

    To get the selected row data correctly when clicking a button, use .selected class to manage the row selection state by adding or removing the selected class:

    $('#DATATABLE tbody').on('click', 'tr', function () {
        $(this).toggleClass('selected');
    });
    
    $('#getSelectedRows').on('click', function () {
        var selectedRows = table.rows('.selected').data(); // Get the data of the selected rows.
        var selectedData = [];
    
        // Iterate through the selected row data.
        selectedRows.each(function (value, index) {
            selectedData.push(value);
        });
    
        // Verify if it is correct.
        alert('the selected rows data:\n' + JSON.stringify(selectedData, null, 2));
    });
    

    Edit:

    But select: {style: 'multi'} is not selecting any of the row in my data table when clicking on it.

    It could be due to version differences. Below are the versions I am using:

    <!-- jQuery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.min.css" />
    
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script>
    

    My test result:

    Test Image