skip to Main Content

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.

2

Answers


  1. 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

    Login or Signup to reply.
  2. DataTables Select is an extension library for DataTables. To use it, you must import the library:

    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.7.0/css/select.dataTables.min.css"/>
    
    <script type="text/javascript" src="https://cdn.datatables.net/select/1.7.0/js/dataTables.select.min.js"></script>
    

    I believe that the 1.7.0 version should be compatible with the DataTables 1.x.x version.

    If your downloaded DataTables package includes the DataTables Select files, you can import from the local file instead of the CDNJS website. Otherwise, you can choose to download the DataTables package by including the Select library but it seems to download with the latest version (DataTables 2.1.4) only. The Select library will be included in the datatables.js/datatables.min.js file and you don’t need to import the library externally as I did on top.

    And enable the multiple selection setting in the DataTables:

    var dataTableOptions = {
      select: {
        style: 'multi',
      },
      ...
    };
    

    Demo @ StackBlitz

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search