首页 > 解决方案 > 在 .NET CORE 的部分视图中使用 Modal JavaScript 在 Ajax Post 之后将不起作用

问题描述

我使用部分视图中的模态显示字段为用户输入数据,并在主屏幕中使用 data-url=@url.action("Create") 调用模态。并在 Partial View 中编写了 Autocomplete JavaScript。在使用 Ajax Post 之前它可以完美运行。但是经过Ajax后,返回时出现错误,JavaScript无法使用。我该如何进行更正?

主视图

<div id="PlaceHolderHere" data-url="@Url.Action("Create")"></div>

阿贾克斯代码

$(function () {
    var PlaceHolderElement = $('#PlaceHolderHere');
    $('button[data-toggle="ajax-modal"]').click(function (event) {
        event.preventDefault();
        var url = $(this).data('url');
        $.get(url).done(function (data) {
            PlaceHolderElement.html(data);
            PlaceHolderElement.find('.modal').modal('show');
        });
    });
    PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {
        event.preventDefault();
        var form = $(this).parents('.modal').find('form');
        var actionUrl = form.attr('action');
        var sendData = new FormData(form.get(0));
        console.log(sendData);
        $.ajax({
            url: actionUrl,
            method: 'post',
            data: sendData,
            processData: false,
            contentType: false,
            cache: false,
            success: function (redata) {
                console.log(redata);
                if (redata.status === "success") {
                    PlaceHolderElement.find('.modal').modal('hide');
                }
                else {
                    var newBody = $('.modal-body', redata);
                    var newFoot = $('.modal-footer', redata);
                    PlaceHolderElement.find('.modal-body').replaceWith(newBody);
                    PlaceHolderElement.find('.modal-footer').replaceWith(newFoot);
                }
            },
            error: function (message) {
                alert(message);
            }
        })
    })
})

JavaScript 部分的局部视图

@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script src="~/bootstrap-autocomplete/dist/latest/bootstrap-autocomplete.min.js"></script>
$('#BossName').autoComplete({
        resolver: 'custom',
        minLength: 2,
        formatResult: function (item) {
            return {
                value: item.value,
                text: "[" + item.value + "] " + item.text,
            }
        },
        noResultsText:'There is no matching data, please confirm whether there is data in the company field',
        events: {
            search: function (qry, callback) {
                // let's do a custom ajax call
                $.ajax(
                    '@Url.Action("GetRolesByAutoComplete","Roles")',
                    {
                        data: {
                            'q': qry,
                            'key': document.getElementById('CompanyCode').value
                        }
                    }
                ).done(function (res) {
                    callback(res)
                });
            }
        }
    });

    $('#BossName').on('autocomplete.select', function (evt, item) {
        console.log(item);
        $('#BossID').val(item.value);
        $('#BossName').val(item.text);
    });

模态部分视图

<div class="modal fade" id="AddEditRoles" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="AddEditRolesLabel">Add New Roles</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <div class="modal-body">
                <form asp-action="Create" id="Edit">
                    <div class="input-group">
                        <span class="input-group-text">@Html.DisplayNameFor(m => m.RolesCode)</span>
                        @if (Model != null && Model.RolesCode != null)
                        {
                            <input asp-for="RolesCode" class="form-control" readonly />
                        }
                        else
                        {
                            <input asp-for="RolesCode" class="form-control" autocomplete="off" />
                        }
                        <span asp-validation-for="RolesCode" class="text-danger"></span>
                    </div>
                    <div class="input-group">
                        <span class="input-group-text">@Html.DisplayNameFor(m => m.Title)</span>
                        <input asp-for="Title" class="form-control" autocomplete="off" />
                        <span asp-validation-for="Title" class="text-danger"></span>
                    </div>
                    <div class="input-group">
                        <span class="input-group-text">@Html.DisplayNameFor(m => m.CompanyCode)</span>
                        <input type="text" asp-for="CompanyCode" class="form-control col-md-3" readonly />
                        <input type="text" id="CompanyName" class="form-control" autocomplete="off"
                               placeholder="Please type Key word" />
                        <span asp-validation-for="CompanyCode" class="text-danger"></span>
                    </div>
                    <div class="input-group">
                        <span class="input-group-text">@Html.DisplayNameFor(m => m.BossID)</span>
                        <input asp-for="BossID" type="text" class="form-control col-md-3" readonly />
                        <input id="BossName" type="text" class="form-control" autocomplete="off"
                               placeholder="Please type Key word" />
                        <span asp-validation-for="BossID" class="text-danger"></span>
                    </div>
                </form>
            </div>

            <div class="modal-footer">
                <div class="text-danger">@Html.ValidationMessage("error")</div>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button id="Save" type="button" class="btn btn-primary" data-save="modal">Save changes</button>
            </div>
        </div>
    </div>
</div>

标签: javascriptasp.net-core-mvcbootstrap-modalasp.net-mvc-partialview

解决方案


您将数据发送到服务器,但当它失败时,您会替换模态内容。

替换 HTML 会破坏已经存在的所有内容,因此您会擦除自动完成插件完成的所有内容。

您需要做的就是再次初始化自动完成功能:

success: function (redata) {
    if (redata.status === "success") {
    } else {
        var newBody = $('.modal-body', redata);
        var newFoot = $('.modal-footer', redata);
        PlaceHolderElement.find('.modal-body').replaceWith(newBody);
        PlaceHolderElement.find('.modal-footer').replaceWith(newFoot);
        // INITIALIZE AUTOCOMPLETE HERE
    }
},

推荐阅读