Change a JS Function to open two different Modal Bootstrap Windows - Asp.Net Core MVC

0

Currently, I have a Modal (modalGenerica) in my Index that generically opens the Create, Edit and Delete views. To open the Create and Edit views, there is no problem, since both open in a modal of the same "size", but that to open the view Delete the modal size should be another.

<div class="modal fade modal-primary" id="modalGenerica" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content"  >
            <div id="contentModal">               
            </div>
        </div>
    </div>
</div>

Then, I created another modal block to open the Delete view:

<div class="modal fade modal-danger" id="pessoaSituacaoDelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div id="contentModalDelete">
            </div>
        </div>
    </div>
</div>

The Problem: My JS Script (which I found on the web) has the logic of opening all views generically in only one modal. Each button (btnCreate, btnEdit, and btnDelete) has the data-modal="" property that is called in the script to generically open the modals. I'm using a DataTable where rows are built and loaded using JavaScript.

$(document).ready(function () {
    $.ajaxSetup({ cache: false });
    // busca los elementos el atributo data-modal y le suscribe el evento click
    $('a[data-modal]').on('click', function (e) {
        // Abre la ventana modal con el formulario solicitado 
        openmodal(this.href);
        return false;
    });  
    
    $('table').on('click', 'a[data-modal]', function (e) {       
        openmodal(this.href);
        return false;       
    });

    $('#modalGenerica').on('hidden.bs.modal', function () {
        $('#contentModal').html('');
    });
    dataTablePrincipalLoad();

});
function openmodal(url) {
    // Hace una petición get y carga el formulario en la ventana modal
    $('#contentModal').load(url, function () {
        $('#modalGenerica').modal({
            keyboard: true
        }, 'show');
        //Enviar o foco para campo Descrição
        $('#modalGenerica').on('shown.bs.modal', function (event) {
            $("#txtPessoaDituacaoId").focus();
        });
        // Suscribe el evento submit
        bindForm(this);
    });

}

function bindForm(dialog) {
    // Suscribe el formulario en la ventana modal con el evento submit

    $('form', dialog).submit(function () {
        if ($(this).valid()) {
            // Realiza una petición ajax
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    // Si la petición es satisfactoria, se recarga la página actual
                    if (result.success) {
                        window.location = window.location;
                    } else {
                        $('#contentModal').html(result);
                        bindForm();
                    }
                }
            });
            return false;
        } else {
            return false;
        }
    });
}

How do I adjust the script to make the Delete view open only in the modal "PersonDeleteStatus"?

// My Index

@model IEnumerable<Retaguarda.Application.ViewModels.PessoaSituacao.PessoaSituacaoViewModel>
@{
    ViewData["Title"] = "Gerenciar Situações de Pessoa";
    //var mensagemObject = TempData["Mensagem"];
}

<div class="panel">
    <div class="panel-heading">
        <h2 class="panel-title">@ViewData["Title"]</h2>
        <div class="page-header-actions">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a asp-action="Index" asp-controller="Home">Home</a></li>
                <li class="breadcrumb-item active">pessoa-situacao-gerenciar/listar-todos</li>
            </ol>
        </div>
    </div>
    <div class="panel-body container-fluid">
        <div class="row">
            <div>
                @if (TempData["Mensagem"] != null)
                {
                    var data = TempData["Mensagem"].ToString();
                    <p>@data.ToString()</p>
                }
            </div>
            <div class="col-md-12">
                <div>
                    <div class="float-left">
                        @*<a a id="btnNovo" asp-action="Create" data-modal="" class="btn btn-success text-white"><i class="icon wb-plus" aria-hidden="true"></i> Nova Situação</a>
                            <a id="btnPesquisaAvancada" class="btn btn-warning text-white"><i class="icon wb-search" aria-hidden="true"></i><span class="hidden-xs"></span> Pesquisa Avançada</a>*@
                        <div class="btn-group btn-group-sm"
                             role="group">
                            <a asp-action="Create" data-modal="" class="btn btn-success text-white" data-toggle="tooltip"
                               data-original-title="Nova Situação" data-container="body">
                                <i class="icon wb-plus" aria-hidden="true"></i>
                                <span class="hidden-xs">Nova Situação</span>
                            </a>
                            <a id="btnPesquisaAvancada" class="btn btn-dark text-white" data-toggle="tooltip"
                               data-original-title="Pesquisa Avançada" data-container="body">
                                <i class="icon wb-search" aria-hidden="true"></i>
                                <span class="hidden-xs">Pesquisa Avançada</span>
                            </a>
                            <div class="btn-group btn-group-sm" role="group">
                                <a data-original-title="Pesquisa Avançada" class="btn  btn-dark text-white dropdown-toggle"
                                   data-toggle="dropdown" aria-expanded="false">
                                    <i class="icon wb-grid-4" aria-hidden="true"></i>
                                    Mais Ações
                                </a>
                                <div class="dropdown-menu" aria-labelledby="exampleGroupDrop2" role="menu">
                                    <a class="dropdown-item" href="javascript:void(0)" role="menuitem"><i class="icon wb-download" aria-hidden="true"></i>Importar</a>
                                    <a class="dropdown-item" href="javascript:void(0)" role="menuitem"><i class="icon wb-upload" aria-hidden="true"></i>Exportar</a>
                                    <a class="dropdown-item" href="javascript:void(0)" role="menuitem"><i class="icon wb-print" aria-hidden="true"></i>Imprimir</a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <br />
        <div id="divPesquisaAvancada" class="busca">
            <div class="panel bg-blue-grey-100">
                <div class="panel-heading">
                    <h2 class="panel-title">Opções Avançadas de Pesquisa</h2>
                </div>
                <div class="panel-body container-fluid">
                    <div class="form-group">
                        @*<div class="col">
                                <input type="checkbox" class="icheckbox-primary" id="inputUnchecked" name="padraoSistemaSearch"
                                       data-plugin="iCheck" data-checkbox-class="icheckbox_flat-blue" checked />
                                <label for="inputUnchecked">Buscar Registros Padrão do Sistema (Não podem ser alterados)</label>
                            </div>
                            <div class="col">
                                <input type="checkbox" class="icheckbox-primary" id="inputUnchecked" name="registrosUsuarioSearch"
                                       data-plugin="iCheck" data-checkbox-class="icheckbox_flat-blue" checked />
                                <label for="inputUnchecked">Buscar Registros </label>
                            </div>*@
                        <p>Não há Opções de Pesquisa.</p>
                    </div>
                    <div class="form-group">
                        <div class="pull-right">
                            <button id="btnPesquisar" class="btn btn-primary"><i class="icon wb-search"></i> Pesquisar </button>
                            <button id="btnFecharPesquisa" class="btn btn-danger"><i class="icon wb-close"></i> Fechar </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        @*<div class="form-group">
                <div class="btn-group" aria-label="Button group with nested dropdown" role="group">
                    <a  data-modal="" href="/pessoa-situacao-gerenciar/editar-situacao/' + 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 data-modal="" href="/pessoa-situacao-gerenciar/remover-situacao/' + 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>
            </div>*@

        <br />
        <div class="panel panel-default">
            <table id="dtPrincipal" class="table table-striped table-bordered center-header table-vcenter" cellspacing="0" width="100%">
                <thead class="bg-blue-grey-100">
                    <tr>
                        <th>
                            ID
                        </th>
                        <th>
                            Descrição
                        </th>
                        <th>
                            Ações
                        </th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>
</div>

@*<div class="modal fade modal-primary" id="modalGenerica" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog modal-dialog-centered" style="width: 800px; height: 500px;">
        <div class="modal-content">
            <div id="contentModal"></div>
        </div>
    </div>
</div>*@

<div class="modal fade modal-primary" id="modalGenerica" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content"  >
            <div id="contentModal">               
            </div>
        </div>
    </div>
</div>

<div class="modal fade modal-danger" id="pessoaSituacaoDelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div id="contentModalDelete">
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="customerHistory" role="dialog">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Customer Data History</h4>
            </div>
            <div class="modal-body">
                <p id="customerHistoryData"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

@section scripts
    {
    <script src="~/js/cadastros/pessoaSituacao/pessoaSituacao.js"></script>
}

// View Delete

@model Retaguarda.Application.ViewModels.PessoaSituacao.PessoaSituacaoViewModel
@{
    ViewData["Title"] = "Excluir Situação";
    Layout = null;
}
<div>
    <form asp-action="Delete">
        @Html.AntiForgeryToken()

        <div class="modal-shadow">
            <div class="modal-header modal-header-primary">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title text-center"> @ViewData["Title"] </h4>
            </div>
            <div class="form-horizontal">
                <vc:summary />
                <div class="panel-body">
                    <p><h4>Tem certeza de que deseja excluir a Situação @Model.Descricao?</h4></p>
                </div>
            </div>
            <div class="modal-footer">
                <div class="col-md-offset-2 col-md-10">
                    <button id="btnExcluir" type="submit" class="btn btn-primary"><i class="icon wb-check"></i> Excluir </button>
                    <button id="btnCancelar" class="btn btn-danger" data-dismiss="modal"><i class="icon wb-close"></i> Cancelar </button>
                </div>
            </div>
        </div>
    </form>
</div>

<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>

<script>
    //Resolve problema de exibição no Modal
    $('#mySelect2').selectpicker({
        dropdownParent: $('#modalGenerica')
    });
    $('#mySelect3').selectpicker({
        dropdownParent: $('#modalGenerica')
    });
    $('#mySelect4').selectpicker({
        dropdownParent: $('#modalGenerica')
    });
    $('#mySelect5').selectpicker({
        dropdownParent: $('#modalGenerica')
    });
</script>


@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

// Java Complete script

$(document).ready(function () {
    $.ajaxSetup({ cache: false });
    // busca los elementos el atributo data-modal y le suscribe el evento click
    $('a[data-modal]').on('click', function (e) {
        // Abre la ventana modal con el formulario solicitado 
        openmodal(this.href);
        return false;
    });  
    
    $('table').on('click', 'a[data-modal]', function (e) {       
        openmodal(this.href);
        return false;       
    });

    $('#modalGenerica').on('hidden.bs.modal', function () {
        $('#contentModal').html('');
    });
    dataTablePrincipalLoad();

});
function openmodal(url) {
    // Hace una petición get y carga el formulario en la ventana modal
    $('#contentModal').load(url, function () {
        $('#modalGenerica').modal({
            keyboard: true
        }, 'show');
        //Enviar o foco para campo Descrição
        $('#modalGenerica').on('shown.bs.modal', function (event) {
            $("#txtPessoaDituacaoId").focus();
        });
        // Suscribe el evento submit
        bindForm(this);
    });

}

function bindForm(dialog) {
    // Suscribe el formulario en la ventana modal con el evento submit

    $('form', dialog).submit(function () {
        if ($(this).valid()) {
            // Realiza una petición ajax
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    // Si la petición es satisfactoria, se recarga la página actual
                    if (result.success) {
                        window.location = window.location;
                    } else {
                        $('#contentModal').html(result);
                        bindForm();
                    }
                }
            });
            return false;
        } else {
            return false;
        }
    });
}

function dataTablePrincipalLoad() {

    $('.dataTables_filter input').attr('placeholder', 'Search...').hide();
    var table = $("#dtPrincipal").DataTable({
        "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
        //"dom": '<"top"i>rt<"bottom"lp><"clear">',
        // "ordering": false,
        "ajax": {
            "url": '/pessoa-situacao-gerenciar/getPessoaSituacao',
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [
            //Estilos Das Colunas
            { className: "align-center", "targets": [0] },
            { className: "align-center", "targets": [2] },

            //Largura das Colunas
            { width: 100, targets: 0 },
            { width: 100, targets: 2 }
        ],
        "columns": [
            { "data": "id", "name": "Id", "autoWidth": true },
            { "data": "descricao", "name": "Descricao", "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="/pessoa-situacao-gerenciar/editar-situacao/' + 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="/pessoa-situacao-gerenciar/remover-situacao/' + 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();
    });

}

//Painel de Pesquisa Avançada
$("#btnPesquisaAvancada").click(function () {
    openPainelPesquisaAvancada();
});
$("#btnFecharPesquisa").click(function () {
    closePainelPesquisaAvancada();
});

function openPainelPesquisaAvancada() {
    $(this).toggleClass();
    $("#divPesquisaAvancada").slideToggle();
}
function closePainelPesquisaAvancada() {
    $("#divPesquisaAvancada").slideToggle();
}
    
asked by anonymous 15.07.2018 / 13:23

1 answer

0

I made an example for you very simple of one of the ways to make the exchange of a class of the same element with jQuery .

  

To see the difference in the size of the modals click page all .

$(document).ready(function() {
			
  $("#btnExcluir").on("click", function() {
    $(".modal-dialog").addClass("modal-lg");  //adicona a classe modal-lg
    $("#texto").text("Modal Large");          //quando o modal Excluir for chamado
  });

  $("#btnEditar").on("click", function() {
    $(".modal-dialog").removeClass("modal-lg"); //exclui a classe modal-lg
    $("#texto").text("Modal Small");            //quando o modal Editar for chamado
  });

})
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<button type="button" class="btn btn-primary" id="btnEditar" data-toggle="modal" data-target="#modal">Editar</button>
<button type="button" class="btn btn-danger" id="btnExcluir" data-toggle="modal" data-target="#modal">Excluir</button>
  
<div class="modal" id="modal" tabindex="-1" role="dialog">
   <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
         <div class="modal-header">
            <h5 class="modal-title">Editar Informações</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
               <span aria-hidden="true">&times;</span>
            </button>
         </div>
         <div class="modal-body">
            <p id="texto"></p>
         </div>
         <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
            <button type="button" class="btn btn-primary">Salvar</button>
         </div>
      </div>
   </div>
</div>  
    
15.07.2018 / 15:59