在 Ajax Post 之后,在 .NET CORE 的分部视图中使用模态 JavaScript 将不起作用

Using Modal JavaScript in the Partial View of .NET CORE will not work after Ajax Post

我在Partial View中使用Modal显示字段给User输入数据,在主界面使用data-url=@url.action("Create")调用Modal . 并在 Partial View 中写了 Autocomplete JavaScript 。 它在使用 Ajax Post 之前完美运行。 但是经过Ajax后,JavaScript在returns时出现错误,无法使用。 我该如何更正?

主视图

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

Ajax代码

$(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>

您向服务器发送数据,但当它失败时您替换模式内容。

替换 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
    }
},