How to delete multiple selected records in a Datatable Bootstrap using Javascript - Asp.net

Asked

Viewed 584 times

1

In my Index I have a Table (Datatable Bootstrap) that allows me to select as many Rows as desired. The datatable lines 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 database deletion functionality of multiple records selected on the grid. Someone knows how to do it?

inserir a descrição da imagem aqui

<table id="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 follows 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, follow my DELETE Action:

[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, follow the code of 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, follow 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,
    });
}

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 you can’t see in your code is where are the ID’s of the ones that match 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);

  });

} );
  • Hi @John Diego Florencio! ID’s are inside the "render" block in the above JS Code: Ex: href="/cep-manage/remove-cep/' + full.id + '. They are stored as lines are loaded from the database.

  • You could post here a JSON example of this request?

  • Yes of course! In the JS block I make an AJAX call, I receive the database information and I rewrite the lines of the table... "url": '/cep-manage/getCEP'... I updated the post with the action...

  • @Master JR. I don’t understand much about ASP.NET, what I was needing is the JSON file of the request that fills Datatable. I notice in your code that the function delete In the answer, the script I put as an example shows just this, that you should create an array containing the values that were selected in Datatable. So Your Action Delete should also change, it has to be ready to receive an Array with these values, and iterate over each value.

  • Hey I quoted above : public Jsonresult getCEP() @João Diego Florencio... When calling getCEP, a json is loaded and passed to that JS block I quoted... Take a look further up... :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.