Problems with Entada mask removal in Partialviews - Asp.Net Core

Asked

Viewed 80 times

1

I’m having trouble with input masks (bootstrap) on all screens. I found the following interesting: All my Views that are returned in the form of "Partialview", the input masks do not work. For testing, when I create a View and a controller that returns a View, everything works correctly. This clearly shows that the problem is caused by the return in Partialview form of my controller.

I have several CRUD Views that are opened in modal form from my Index. They only work if the return is Partialview. Only that the entrance masks do not work at all... Someone knows how to solve this?

inserir a descrição da imagem aqui

 [HttpGet]
        [Authorize(Policy = "CanWriteCepData")]
        [Route("cep-gerenciamento/editar-cep/{id}")]
        public IActionResult Edit(string id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var cepViewModel = _cepAppService.GetByCepId(id);

            if (cepViewModel == null)
            {
                return NotFound();
            }

            return PartialView(cepViewModel);
        }

@using SistemaComercial.Domain.ValueObjects
@model SistemaComercial.Application.ViewModels.Cep.CepViewModel
@{
    ViewData["Title"] = "Editar CEP";
}

<div>
    <form asp-action="Edit">
        @Html.AntiForgeryToken()

        <div class="modal-shadow">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="false">×</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title text-center"> @ViewData["Title"] </h4>
            </div>
            <div class="form-horizontal">
                <div id="validationSummary" class="text-center">
                    <vc:summary />
                </div>
                <div class="panel-body">
                    <div class="form-group">
                        <label asp-for="CepId" class="col-md-2 control-label"></label>
                        <div class="col-md-3">
                            <input id="txtCep" asp-for="CepId" class="form-control" data-plugin="formatter" data-pattern="[[99999]]-[[999]]" />
                            <span asp-validation-for="CepId" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label asp-for="Endereco" class="col-md-2 control-label"></label>
                        <div class="col-md-10">
                            <input id="txtEndereco" asp-for="Endereco" class="form-control text-uppercase" />
                            <span asp-validation-for="Endereco" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label asp-for="Complemento" class="col-md-2 control-label"></label>
                        <div class="col-md-5">
                            <input asp-for="Complemento" class="form-control text-uppercase" />
                            <span asp-validation-for="Complemento" class="text-danger"></span>
                        </div>
                        <label asp-for="Bairro" class="col-md-1 control-label"></label>
                        <div class="col-md-4">
                            <input asp-for="Bairro" class="form-control text-uppercase" />
                            <span asp-validation-for="Bairro" class="text-danger"></span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label asp-for="Cidade" class="col-md-2 control-label"></label>
                        <div class="col-md-7">
                            <input id="txtDescricao" asp-for="Cidade" class="form-control text-uppercase" />
                            <span asp-validation-for="Cidade" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label asp-for="UF" class="col-md-2 control-label"></label>
                        <div class="col-md-2">
                            <input asp-for="UF" class="form-control text-uppercase" maxlength="2" />
                            <span asp-validation-for="UF" class="text-danger"></span>
                        </div>
                        <div class="col-md-5">
                            <div class="checkbox-custom checkbox-default">
                                <input type="checkbox" asp-for="PadraoSistema" disabled />
                                <label asp-for="PadraoSistema"></label>
                            </div>
                            <span asp-validation-for="PadraoSistema" class="text-danger"></span>
                        </div>
                       
                    </div>
                    <div class="modal-footer">
                        <button id="btnSalvar" type="submit" class="btn btn-primary"><i class="icon wb-check"></i> Salvar </button>
                        <a class="btn btn-danger" data-dismiss="modal">
                            <span title="Fechar" class="icon wb-close"></span> Fechar
                        </a>
                    </div>
                </div>
            </div>
        </div>

    </form>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    @*<script type="text/javascript">
            $(function () {
                //allow validation framework to parse DOM
                $.validator.unobtrusive.parse('form');
            });
        </script>*@
}

//Campo da View Edit contendo a Máscara de Entrada de CEP
 <div class="form-group">
                        <label asp-for="CepId" class="col-md-2 control-label"></label>
                        <div class="col-md-3">
                            <input id="txtCep" asp-for="CepId" class="form-control" data-plugin="formatter" data-pattern="[[99999]]-[[999]]" />
                            <span asp-validation-for="CepId" class="text-danger"></span>
                        </div>
                    </div>

$(document).ready(function () {
    $.ajaxSetup({ cache: false });
    // busca os elementos do atributo data-modal e o vincula ao evento click
    $('a[data-modal]').on('click', function (e) {
        // Abre a janela modal com o formulário solicitado 
        openmodal(this.href);
        return false;
    });
    $('table').on('click', 'a[data-modal]', function (e) {
        openmodal(this.href);
        return false;
    });

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

    dataTablePrincipalLoad();

});

function openmodal(url) {
    // Faz uma requisição Get e carrega o formulário na janela modal
    $('#contentModal').load(url, function () {
        $('#modalCep').modal({
            keyboard: true
        }, 'show');
        //Enviar o foco para campo Descrição
        $('#modalCep').on('shown.bs.modal', function (event) {
            $("#txtCep").focus();   
        });
        // Vincula o evento submit
        bindForm(this);
    });
}
function bindForm(dialog) {
    // Vincula o formulário na janela modalcom o evento submit
    $('form', dialog).submit(function () {
        if ($(this).valid()) {
            // Realiza uma querisição ajax
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    // Se a requisição for satisfatória, a página atual é recarregada
                    if (result.success) {
                        window.location = window.location;
                        window.location.reload(); //Ajuda na exclusao, atualizando o grid

                    } 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">',
        "ajax": {
            "url": '/cep-gerenciamento/getCeps',
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [
            { className: "align-center", "targets": [3] },
            { className: "align-right", "targets": [0] },
            {
                "targets": [0],
                "visible": true,
                "searchable": false,
                "render": function (data, type, row) {
                    return data.substring(0, 5) + "-" + data.substring(5);
                }
            }
        ],
        "columns": [
            { "data": "cepId", "name": "Cep", "autoWidth": true },
            { "data": "endereco", "name": "endereco", "autoWidth": true },
            { "data": "complemento", "name": "complemento", "autoWidth": true },
            { "data": "bairro", "name": "bairro", "autoWidth": true },
            { "data": "cidade", "name": "cidade", "autoWidth": true },
            { "data": "uf", "name": "uf", "autoWidth": true },
            {

                "render": function (data, type, full, meta) {
                    return '<a btnEditar title="Editar" data-modal="" href="/cep-gerenciamento/editar-cep/' + full.cepId + '" class="btn btn-sm btn-icon btn-pure btn-default on-default edit-row"><span class="icon-2x wb-edit"></span></a> |' +
                        '<a title="Detalhes" data-modal="" href="/cep-gerenciamento/detalhes-cep/' + full.cepId + '" class="btn btn-sm btn-icon btn-pure btn-default on-default footable-row-detail-row"><span class="icon-2x wb-search"></span></a> |' +
                        '<a title="Excluir" data-modal="" href="/cep-gerenciamento/remover-cep/' + full.cepId + '" class="btn btn-sm btn-icon btn-pure btn-default on-default remove-row"><span class="icon-2x wb-trash"></span></a> |' +
                        '<a title="Histórico" class="btn btn-sm btn-icon btn-pure btn-default on-default clockpicker" data-toggle="modal" data-target="#pessoaHistory" data-original-title="Histórico"><span class="icon-2x wb-time"></span></a>'
                }
            }
        ],
        "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();
    });
};

1 answer

2

This part cannot be inside the partial view, because @section doesn’t work inside her:

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    @*<script type="text/javascript">
            $(function () {
                //allow validation framework to parse DOM
                $.validator.unobtrusive.parse('form');
            });
        </script>*@
}

just put @Section inside the main view that solves your problem.

A guide in English well explained link here

  • It’s @Hudsonph... The problem is that my View EDIT is already the main view... In my Controller it is returned in the form of Partialview, so my Modals windows work properly.

  • @Jalberroman your problem is between controller return and Section, to test put your sricpt in _layout if it works the problem is the @section

  • I did several @Hudsonph tests, including the ones you suggested and didn’t work. As you suggested, it could be some "problem in the return of my controller"... I updated the Post with my Script... all Create, Edit, Delete and Details buttons make use of the data-modal attribute-""... It is that when clicked, the JS triggers the click event and a load is made in the modal window dynamically... There is some problem in the shipment as it is failing to set the masks at this time.

  • I say this, because when I create a view not to be opened in a Modal way, it works correctly, even if I put the block of scripts Section... Do you have any idea what it could be?

  • @section has a problem with partian view, other tests to do add console.log("TEST"); at the beginning of each function and in place of $(function () { swap for $(document).ready(function () { if "TEST" appears and js does not work its path is wrong

  • In the console, appeared two "TEST", the modal ran normally...

  • if it worked then your problem is in that line @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} check if the path is correct or use full text

  • I’m in doubt about the function bindForm... It has an if and Else.... I put a Console in both and it is not falling... Is it not the request ajax? Renderpartialasync’s path is correct..... That’s what puzzles me.. Wouldn’t the problem be in Bind?

  • All the possibilities have been exhausted... Wouldn’t you like to take a look at the project via Teamviewer? So if we could find a solution, we could post here to help other people...

  • I can see in 2:00-3:00

  • No problem... I can wait for you. Thanks man

Show 7 more comments

Browser other questions tagged

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