Problems with embedding masks in PartialViews - Asp.Net Core

1

I'm having problems with 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 tests, 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 PartialView return from my controller.

I have several CRUD Views that are opened in modal form from my Index. They only work if the return is PartialView. But the incoming mascots do not work at all ... Does anyone know how to solve this?

 [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();
    });
};
    
asked by anonymous 11.06.2018 / 13:14

1 answer

2

This part can not be inside the partial view, because @section does not work inside it:

@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 well-explained English guide link here

    
11.06.2018 / 13:49