Search code examples
javascriptasp.net-core-mvcbootstrap-modalasp.net-mvc-partialview

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


I use the Modal display field in the Partial View to input data for the User, and use data-url=@url.action("Create") in the main screen to call Modal. And wrote Autocomplete JavaScript in Partial View. It works perfectly before using Ajax Post. But after going through Ajax, the JavaScript cannot be used when it returns because of an error. How can I make corrections?

Main View

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

Ajax Code

$(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);
            }
        })
    })
})

Partial View of JavaScript part

@{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);
    });

Partial View of Modal

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

Solution

  • You send data to the server, but when it fails you replace modal contents.

    Replacing HTML destroys everything that was already there, so you wipe everything that was done by your autocomplete plugin.

    All you need to do is to initialize autocomplete again:

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