How to delete multiple selected records in a DataTable Bootstrap using JavaScript - Asp.net

1

In my Index I have a Table (DataTable Bootstrap) that allows me to select as many rows as I want. Datatable rows are loaded dynamically using JS. Each line stores the registry id: ("href=" / cep-manage / remove-cep / '+ full.id ") at the time the lines are loaded from the database.

I need to implement the deletion functionality in the database of multiple records selected on the grid. Does anyone know how to do it?

<tableid="dtPrincipal" class="table table-striped table-bordered center-header table-vcenter table-responsive-lg" data-role="content" data-plugin="selectable" data-row-selectable="true" cellspacing="0" width="100%">
    <thead class="bg-blue-grey-100">
        <tr>
            <th>
                <span class="checkbox-custom checkbox-primary">
                    <input class="selectable-all" type="checkbox">
                    <label></label>
                </span>
            </th>
            <th>
                CEP
            </th>
            <th>
                Logradouro
            </th>
            <th>
                Cidade
            </th>
            <th>
                UF
            </th>
            <th>
                Ações
            </th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

Below is the complete DataTable javascript:

function dataTablePrincipalLoad() {

    $('.dataTables_filter input').attr('placeholder', 'Search...').hide();
    var table = $("#dtPrincipal").DataTable({   
        //"select": true, //Habilita a seleção no Grid
        //select: {
        //    style: 'single'
        //}, // Determina o stilo de seleção a ser usada no grid
        "processing": true, // for show progress bar
        "serverSide": true, // for process server side
        "filter": true, // this is for disable filter (search box)
        "orderMulti": false, // for disable multiple column at once
        "ordering": true, //Ativar/Desativar Ordenação de colunas 
        "order": [[1, "asc"]], //Ordenar da segunda coluna em diante para não atrapalhar a coluna [0] da seleção
        //"sDom": '<"top"i>rt<"bottom"flp><"clear">',//Posiciona  a caixa de busca abaixo do datatable
        "ajax": {
            "url": '/cep-gerenciar/getCEP',
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [
            //Estilos Das Colunas
            { className: "align-center", "targets": [0] },
            { className: "align-center", "targets": [1] },
            { className: "align-left", "targets": [2] },
            { className: "align-left", "targets": [3] },
            { className: "align-center", "targets": [4] },
            { className: "align-center", "targets": [5] },

            //Largura das Colunas
            { width: 50, targets: 1 },
            { width: 390, targets: 2 },
            { width: 200, targets: 3 },
            { width: 10, targets: 4 },
            { width: 100, targets: 5 },
            {
                "targets": [1],
                "visible": true,
                "searchable": false,
                "render": function (data, type, row) {
                    return data.substring(0, 5) + "-" + data.substring(5);
                }
            },
            { "orderable": false, "targets": 0}

        ],
        "columns": [
            {
                "render": function (data, type, full, meta) {
                    return '<td><span class="checkbox-custom checkbox-primary"><input class="selectable-item" type="checkbox"><label></label></span></td>';
                }
            },
            { "data": "codigoEnderecamentoPostal", "name": "CodigoEnderecamentoPostal", "autoWidth": true},
            { "data": "logradouro", "name": "Logradouro", "autoWidth": true },           
            { "data": "cidade", "name": "cidade", "autoWidth": true },
            { "data": "uf", "name": "UF", "autoWidth": true },
            {
                "render": function (data, type, full, meta) {
                    return '<div class="btn-group" aria-label="Button group with nested dropdown" role="group"><a id="btnEditar" data-modal="" href="/cep-gerenciar/editar-cep/' + full.id + '"class="btn btn-sm btn-icon btn-default btn-outline" title="Visualizar/Editar"><i class="icon wb-edit" aria-hidden="true"></i></a><a id="btnExcluir" data-modal="" href="/cep-gerenciar/remover-cep/' + full.id + '"  class="btn btn-sm btn-icon btn-default btn-outline" title="Excluir"><i class="icon wb-trash" aria-hidden="true"></i></a><div class="btn-group" role="group"><a title="Mais Ações" class="btn btn-sm btn-outline btn-default dropdown-toggle" id="exampleGroupDrop2" data-toggle="dropdown" aria-expanded="false"><i class="icon wb-grid-4" aria-hidden="true"></i></a><div class="dropdown-menu" aria-labelledby="exampleGroupDrop2" role="menu"><a class="dropdown-item" href="javascript:void(0)" role="menuitem"><i class="icon wb-time" aria-hidden="true"></i>Histórico</a></div></div></div>';
                }
            }
        ],
        "language": {
            "sEmptyTable": "Nenhum registro encontrado",
            "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
            "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
            "sInfoFiltered": "(Filtrados de _MAX_ registros)",
            "sInfoPostFix": "",
            "sInfoThousands": ".",
            "sLengthMenu": "_MENU_ resultados por página",
            "sLoadingRecords": "Carregando...",
            "sProcessing": "Processando...",
            "sZeroRecords": "Nenhum registro encontrado",
            "sSearch": "Pesquisar",
            "searchPlaceholder": "Digite algo...",
            "oPaginate": {
                "sNext": "Próximo",
                "sPrevious": "Anterior",
                "sFirst": "Primeiro",
                "sLast": "Último"
            },
            "oAria": {
                "sSortAscending": ": Ordenar colunas de forma ascendente",
                "sSortDescending": ": Ordenar colunas de forma descendente"
            }
        }
    });  

    $('.search-input').on('keyup change', function () {
        var index = $(this).attr('data-column'),
            val = $(this).val();
        table.columns(index).search(val.trim()).draw();
    });

}

Below is my Action DELETE:

[HttpPost, ActionName("Delete")]
[Authorize(Policy = "CanRemoveCEPData")]
[Route("cep-gerenciar/remover-cep/{id:int}")]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(int id)
{
    _CEPAppService.Remove(id);

    if (!IsValidOperation()) return View(_CEPAppService.GetById(id));

    return Json(new { success = true, message = "CEP Excluído!" });

}

Below is the code for the Delete button:

<a class="dropdown-item" href="javascript:void(0)" onclick="excluirRegistrosSelecionadosDataTable()" role="menuitem"><i class="icon wb-trash" aria-hidden="true"></i>Excluir Selecionados</a>

Below is the Action code that loads the CEPS:

[HttpPost]
[Route("cep-gerenciar/getCEP")]
public JsonResult getCEP()
{
    var draw = Request.Form["draw"];
    var start = Request.Form["start"];
    var length = Request.Form["length"];

    var search = Request.Form["search[value]"];

    int pageSize = !string.IsNullOrEmpty(length) ? Convert.ToInt32(length) : 0;
    int skip = !string.IsNullOrEmpty(start) ? Convert.ToInt32(start) : 0;
    int totalRecords = 0;
    int recordsFiltered = 0;

    var cep = _CEPAppService.GetPaginated(search, skip, pageSize, out totalRecords, out recordsFiltered, true);

    return Json(new
    {
        draw = draw,
        recordsFiltered = recordsFiltered,
        recordsTotal = totalRecords,
        data = cep,
    });
}
    
asked by anonymous 28.12.2018 / 20:56

1 answer

1

I've done something similar, but instead of using the checkbox I created a selection by clicking on the line. One thing that you can not see in your code is where the ID's belong to your database.

$(document).ready(function() {

$('.dataTables_filter input').attr('placeholder', 'Search...').hide();
var table = $("#dtPrincipal").DataTable({ 

        data:[

        {0:'<input type="checkbox" class="selectable-item" id="">', 1: 123123, 2: 'rua', 3: 'Eunapolis', 4: 'ba', 5:'', 6: 'id1' },
        {0:'<input type="checkbox" id="<v></v>">', 1: 1, 2: 'rua', 3: 'Eunapolis', 4: 'ba', 5:'', 6: 'id2' },
        {0:'<input type="checkbox" id="checkbox">', 1: 2, 2: 'caminho', 3: 'Eunapolis', 4: 'ba', 5:'', 6: 'id3' },
        {0:'<input type="checkbox" id="checkbox">', 1: 3, 2: 'rua', 3: 'as', 4: 'ba', 5:'', 6: 'idX' },
        {0:'<input type="checkbox" id="checkbox">', 1: 4, 2: 'rua', 3: 'Eunapolis', 4: 'ba', 5:'', 6: 'id4' }
        ,{0:'<input type="checkbox" id="checkbox">', 1: 5, 2: 'rua', 3: 'Eunapolis', 4: 'ba', 5:'', 6: 'id5' }
        ,{0:'<input type="checkbox" id="checkbox">', 1: 6, 2: 'rua', 3: 'Eunapolis', 4: 'ba', 5:'', 6: 'id6' }

        ]
});  
var excluir_esses_valores = [];
//Crie um array que você possa adicionar todas as ID's selecionadas na 
//tabela e depois faça uma requisição para seu servidor com esse valores
$("#dtPrincipal  tbody").on('click', 'tr', function()
{     
 var row = table.row(this).data();

  $(this).addClass('selected');  
  excluir_esses_valores.push(row[6]);
  console.log(excluir_esses_valores);

  });

} );
    
29.12.2018 / 11:17