Scripts stop when I open Modal in a Partial View for the second time

Asked

Viewed 123 times

0

My first question here.

I am developing my first system using Asp.Net MVC.

In a View I call a Modal whose modal-content is a Partialview containing scripts (jQuery). When I open Modal for the first time everything happens as expected, but if I close Modal and open again the scripts stop responding. The modal-container I put it on _Layout, because then I can reuse it in other Modals. In _Layout there are also scripts for the "standard" events of the Modals as the below that clears the cache for when a new modal is loaded:

  $('#modal-container').on('hidden.bs.modal', function () {
        $(this).removeData('bs.modal');
    });

If I remove this event the scripts work even when I open Modal for the second time, but Modal is cached and when opening a new Modal the first Modal is always loaded.

You follow my code: Note: I have hidden the parts that I consider not relevant to the question.

Createedit.cshtml

Call Action back to Partialviewm

                        <div class="col-md-1 form-group">
                            @Html.LabelFor(model => model.Evento.CodChamada, "Cod Evento.")
                            <div class="input-group">
                                @Html.TextBoxFor(model => model.Evento.CodChamada, new { @class = "form-control" })
                                <a href="@Url.Action("OpenSearchEvento", "Formando")" id="btnSearchEvento" class="modal-link input-group-addon">
                                    <i class="fa fa-search"></i>
                                </a>
                            </div>
                        </div>

Formandocontroller.Cs

 [HttpGet]
    public ActionResult OpenSearchEvento(SearchViewModel searchValues)
    {
        var model = GetEventos(searchValues);

        return PartialView("_SearchEvento", model);
    }

Searchevento.cshtml

    $(function () {
        debugger;
        $('#modal-style').css('width', '1250px');
        $('#btnCreate, #actives-only').hide();

        $('#table-eventos tr').on('click', function () {
            $(this).addClass('selected')
                .siblings()
                .removeClass('selected')
                .css('font-weight', 'normal');

            var selectedSearchItem = $(this).find('td:first').html();
            $('.selected').css('font-weight', 'bold');

        });

        $('#btnSelectEvento').on('click', function (e) {
            e.preventDefault();
            var codChamadaEvento = $('#table-eventos tr.selected td:eq(0)').text();
            var nomeEvento = $('#table-eventos tr.selected td:eq(1)').text();
            var EventolId = $('#table-eventos tr.selected').find('td:first').attr('data-evento-id');

            if (lastEventoId != EventolId) {

                if ($('#IsControlaRifa').is(':checked')) {
                    bootbox.confirm({
                        title: 'Alterar Evento',
                        message: 'Ao alterar o Evento do Formando Todas as Rifas do Formando serão excluídas',
                        buttons: {
                            cancel: {
                                label: '<i class="fa fa-times"></i> Cancelar',
                                className: "btn-default"
                            },
                            confirm: {
                                label: '<i class="fa fa-check"></i> OK',
                                className: "btn-danger"
                            }
                        },
                        callback: function (result) {
                            if (result) {
                                $.ajax({
                                    url: '/Formando/DeleteAllRifasFormando',
                                    ajaxasync: true,
                                    cache: false,
                                    method: 'POST',
                                    data: { id: formandoId },
                                    datatype: "text/html"
                                })
                                    .done(function () {
                                        $('#rifas-evento > tbody').html('');
                                        $($('#tabs').find('li')[3]).hide();
                                        $('#IsControlaRifa').prop('checked', false);
                                        bootbox.alert('As Rifas do Formando foram excluidas com sucesso!');
                                        $('#IsControlaRifa').addClass('readOnly');
                                        $('#btnCreateReset').prop('disabled', true);
                                        $('#btnReturn').attr('disabled', 'disabled');
                                    })
                                    .fail(function () {
                                        bootbox.alert('O registro não existe!')
                                    });
                            }
                            $('#IsControlaRifa').prop('checked', true);
                            bootbox.hideAll();
                        }
                    });
                }
            }

            $('#Evento_CodChamada').val(codChamadaEvento);
            $('#Evento_NomeEvento').val(nomeEvento);
            $('#EventoId').val(EventolId)

            $('#modal-container').modal('hide');

        });

        $('#btnSearch').on('click', function (e) {
            e.preventDefault();
            var searchTerm = $('#SearchTerm').val();
            var searchItem = $('#SearchItem').val();
            var isPartial = $('#IsPartial').is(':checked');

            var searchViewModel = {
                'IsPartial': isPartial,
                'IsActivesOnly': true,
                'SearchTerm': searchTerm,
                'SearchItem': searchItem
            }

            $.ajax({
                url: '/Formando/SearchEvento',
                type: 'POST',
                datatype: 'json',
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(searchViewModel),
                success: function (data) {
                    if (data != null && data.length > 0) {

                        for (i in data) {
                            var template = $('#eventotpl').html();
                        }

                        var html = Mustache.to_html(template, data);

                        $('#table-eventos tbody')
                            .empty()
                            .html(html);
                    }
                    else
                        bootbox.alert('A pesquisa não retornou resultados!');
                },
                error: function () {
                    bootbox.alert("Não foi possível Alterar o Contrato do Formando!")
                }
            })
            debugger;
        });

    });
</script>
<script id="eventotpl" type="text/template">
    {{#.}}
    <tr>

        <td class="rv-cod-chamada" data-evento-id={{Id}}>{{CodChamada}}</td>
        <td>{{NomeEvento}}</td>
        <td class="rv-active-icon">{{#IsControlaRifa}} <span><i class='glyphicon glyphicon-ok'></i></span> 
                    {{/IsControlaRifa}} {{^IsControlaRifa}} <i class='glyphicon glyphicon-remove'></i></td> {{/IsControlaRifa}}
    </tr>

    {{/.}}
</script>

1 answer

0

After much research I managed to find the solution!

The point is that when a modal is created (called for the first time) it is attached to the specified in data-target. When we close and open again the modal, only the method toggle() is called and therefore the content of the modal is not updated.

The solution is then to "destroy" the modal before a new call.

In my case the scripts stopped working because in fact they were not even loaded because they had been "destroyed". To solve, in the event click of the buttons that call the modals url which contains the content of the modal and I used the load method to (re)load the new content.

 $('body').on('click', '.modal-link', function (e) {
                e.preventDefault()
                var button = $(e.relatedTarget); 
                var url = button.attr("href");
                var modal = $(this);
                modal.find('.modal-content').load(url);
            });

In addition to destroying the modal, I also changed the code to empty the modal-content and now I can close and open the modal and everything works correctly. In addition it is possible to open a new modal with another content.

$('#modal-container').on('hidden.bs.modal', function () {
                $(this).removeData('bs.modal');
                $('#modal-container .modal-content').empty();

            });

Browser other questions tagged

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