Store selected rows id

2019-08-17 06:43发布

I have a datatable loaded from a query from my database. (+/- 10000 records) The idea is that the user should be able to select multiple records to be later processed

First i thought to add a column with checkbox for the selection then when user is done with all his selection the application keep track of all selected rows then progress to the next step with "Next Button" some where on the page, but after 12 hours of trying i couldn't do it.

Then i thought to make it simpler by adding a button in each row so that every time the user clicks on this button the application save the selected id in a session variable.

<div class="panel-body">

<table id="userTable" class="table display compact order-column">
    <thead>
    <tr>
        <th>Select</th>
        <th>Name</th>
        <th>City</th>
        <th>Phone</th>
        <th>Zipcode</th>
    </tr>
    </thead>  
</table>

@section Scripts {
@Scripts.Render("~/bundles/datatable")
<script type="text/javascript">


    $(document).ready(function () {

        var ids;
        var mytable = $('#userTable').DataTable({


            "sDom": 'ltipr',
            "bServerSide": true,
            "ajax": {
                "beforeSend": AjaxBegin,
                "type": "POST",
                "url": '/LocationModifier/UserHistory',
                "contentType": 'application/json; charset=utf-8',
                'data': function (data) { return data = JSON.stringify(data); },
                'complete': AjaxComplete
            },


            "bProcessing": false,
            "orderMulti": false,
            "scrollX": true,
            "deferRender": true,
            "searchDelay": 7000,
            "fixedHeader": {
                "header": true,
                "footer": true
            },

            "columnDefs": [
                { "defaultContent": "-", "targets": "_all" },
                { "className": "text-center custom-middle-align", "targets": [0, 1, 2, 3, 4, ] },
            ],

            "colReorder": true,

            "lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],



            "columns": [
                 {
                     "title": "Select",
                     "data": "ID",
                     "searchable": false,
                     "sortable": false,
                    "render": function (data, type, full, meta) {

                         return '<a href="@Url.Action("AddToCache", "LocationModifier")?id=' + data + '&source=0" class="editUser"><span class="glyphicon glyphicon-pencil btn-sm btn-info"></span></a>';
                     }
                 },

                { "data": "Name", "orderable": false },
                { "data": "City", "orderable": true },
                { "data": "Phone", "orderable": true },
                { "data": "Zipcode", "orderable": false },

            ],
            "order": []

        });

    });


</script>

}

public ActionResult AddToCache(int id)
    {
        GetRecordAndAddeToCache(id);
        // what should i return here, the page should not be refreshed????
    }

2条回答
【Aperson】
2楼-- · 2019-08-17 06:43

You can use datatable's Row selection feature to achieve what you are trying to do.

$(document).ready(function() {
    var table = $('#userTable').DataTable();

    $('#userTable tbody').on( 'click', 'tr', function () {
        $(this).toggleClass('selected');
    } );

    $('#submitButtonId').click( function () {
        alert( table.rows('.selected').data().length +' row(s) selected' );
        // You can use  table.rows('.selected').data()  to get all the selected Data
    } );
} );

Reference

查看更多
forever°为你锁心
3楼-- · 2019-08-17 06:52

There's no problem to implement your initial approach:

  • use some global set that will store selected row id's, like var rowsSelected = new Set();
  • add/delete id of the row being checked to that global variable upon clicking selection checkbox:
$('.markSelected').on('click', function () {
    const selectedRowId = dataTable.row($(this).closest('tr')).data().id;
    $(this).prop('checked') ? rowsSelected.add(selectedRow) : rowsSelected.delete(selectedRow);
});
  • upon table re-rendering append checkboxes to the first column and set those checked if rendered row id is present within rowsSelected:
render: function (data) {
    return `<input type="checkbox" ${rowsSelected.has(data.id) ? 'checked' : ''}></input>`;
}

The complete demo, implementing that concept:

//table source
const srcData = [
  {id: 1, item: 'apple', cat: 'fruit'},
  {id: 2, item: 'pear', cat: 'fruit'},
  {id: 3, item: 'carrot', cat: 'vegie'},
  {id: 4, item: 'tomato', cat: 'vegie'},
  {id: 5, item: 'cucumber', cat: 'vegie'}
];

//global variable that stores selected item id's
const selectedRows = new Set();

//datatables initialization
const dataTable = $('#mytable').DataTable({
  dom: 't',
  data: srcData,
  columns: [
    {data: null, render: function(data){
      return `<input class="markSelected" type="checkbox" ${selectedRows.has(data.id) ? 'checked' : ''}></input>`;
    }},
    {data: 'item', title: 'item'},
    {data: 'cat', title: 'cat'}
  ]
});

//selection checkboxes click handler
$('#mytable').click('.markSelected', function(){
  const selectedRowId = dataTable.row($(event.target).closest('tr')).data().id;
  $(event.target).prop('checked') ? selectedRows.add(selectedRowId) : selectedRows.delete(selectedRowId);
});

//proceed to the next step with selected row id's
$('#nextStep').on('click', function(){
  console.log([...selectedRows]);
});
<!doctype html>
<html>
<head>
  <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
  <table id="mytable"></table>
  <button id="nextStep">Next Step</button>
</body>
</html>

查看更多
登录 后发表回答