存储选定的行ID [英] Store selected rows id

查看:68
本文介绍了存储选定的行ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数据库查询中加载了一个数据表. (+/- 10000条记录) 想法是用户应该能够选择多个记录以供以后处理

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

首先,我想为选择添加一个带有复选框的列,然后在用户完成所有选择后,应用程序会跟踪所有选定的行,然后使用下一步按钮"进入页面上某些位置的下一步,经过12个小时的尝试,我无法做到.

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.

然后,我想通过在每行中添加一个按钮来简化操作,以便用户每次单击该按钮时,应用程序会将选定的ID保存在会话变量中.

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????
    }

推荐答案

实现初始方法没有问题:

There's no problem to implement your initial approach:

  • 使用一些将存储选定行ID的全局集,例如var rowsSelected = new Set();
  • 在单击选择复选框后,将要检查的行的ID添加/删除到该全局变量:
$('.markSelected').on('click', function () {
    const selectedRowId = dataTable.row($(this).closest('tr')).data().id;
    $(this).prop('checked') ? rowsSelected.add(selectedRow) : rowsSelected.delete(selectedRow);
});

  • 在表重新呈现时,将复选框附加到第一列,并设置是否选中在rowsSelected中是否存在呈现的行ID的复选框:

    • 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>

      这篇关于存储选定的行ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆