Using select2-autocomplete in modal

51 Views Asked by At

if I were to briefly explain my problem; I want to send the Select2-Autocomplete operation to the BaseController according to the parameters I give and get the relevant data. The problem I encounter here is that I do not experience any problems when I am working on a normal page, but when I do the same operation on the modal, I cannot even send a request to the BaseController. I am waiting for your help for this problem. Below I have js codes that will help.

Tools.JS
function CallSelect2() {
    $('.Select2').select2(
        {
            escapeMarkup: function (m) {
                return m;
            }
        });
    $('.Select2-Autocomplete').each(function () {
        var selectElement = $(this);

        var modalContent = selectElement.closest('.modal').find('.modal-content');

        selectElement.select2({
            dropdownParent: modalContent.length ? modalContent : $('body'),
            closeOnSelect: true,
            placeholder: 'Select',
            minimumInputLength: 3,
            width: '100%',
            ajax: {
                url: '/Base/Search_Select2',
                type: 'post',
                dataType: 'json',
                delay: 50,
                data: function (params) {
                    return {
                        prefix: params.term,
                        Params: selectElement.attr("Params"),
                        TargetID: selectElement.attr("TargetID"),
                        TableName: selectElement.attr("TableName")
                    };
                },
                processResults: function (data) {
                    return {
                        results: $.map(data, function (item) {
                            return { id: item.Id, text: item.Name };
                        })
                    };
                },
                cache: true
            },
            escapeMarkup: function (markup) { return markup; }
        });
    });
}

Product.JS
function OpenModal1() {
    $('#PageModal1').modal('show').on('shown.bs.modal', function () {
        console.log("Modal gösterildi, CallSelect2 çağrılıyor");

        $('.Select2-Autocomplete').select2({
            dropdownParent: $('#PageModal1 .modal-content'),
        });
    });
}

$(function () {
    CallSelect2();
});

View Page
<div class="modal fade" id="PageModal1" tabindex="-1" aria-labelledby="PageModal1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title Rb" id="titleModal1">Add New Component</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">                            
                <div class="row">
                    <div class="col col-12">
                        <label class="FormLabel-b">Used Poduct / Raw</label>
                        
                        <select class="form-select Select2-Autocomplete" Title="Product" id="M_UsedProductID" Params="">
                            <option value="0">Select</option> 
                        </select>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <a id="BtnUpsert" onclick="OptModal1()" class="btn btn-primary">Add New Item</a>
            </div>
        </div>
    </div>
</div>
<script src="~/js/Views/Commerce/Product_Component.js"></script>
1

There are 1 best solutions below

0
Fengzhi Zhou On

Your problem is caused by the incorrect process of loading and initializing the modal component and select2 component. Here is the sample code you can refer.

View page

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div class="modal fade" id="PageModal1" tabindex="-1" aria-labelledby="PageModal1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title Rb" id="titleModal1">Add New Component</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col col-12">
                        <label class="FormLabel-b">Used Poduct / Raw</label>

                        <select class="form-select Select2-Autocomplete" Title="Product" id="M_UsedProductID" Params="">
                            <option value="0">Select</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <a id="BtnUpsert" onclick="OptModal1()" class="btn btn-primary">Add New Item</a>
            </div>
        </div>
    </div>
</div>

<script src="~/js/Tools.js"></script>
<script src="~/js/Product.js"></script>

Product.js

function OpenModal1() {
    $('#PageModal1').modal('show').on('shown.bs.modal', function () {
        console.log("Modal is shown, initializing Select2 components.");
        CallSelect2(); // Call this function to initialize Select2 components in the modal.
    });
}

$(function () {
    OpenModal1();  //Your code snippet is not complete and this part is confusing, so I changed it to start the modal
});

Tools.js

function CallSelect2() {
    $('.Select2').select2({
        escapeMarkup: function (markup) {
            return markup;
        }
    });

    $('.Select2-Autocomplete').each(function () {
        var selectElement = $(this);
        var modalContent = selectElement.closest('.modal').find('.modal-content');

        selectElement.select2({
            dropdownParent: modalContent.length ? modalContent : $('body'),
            closeOnSelect: true,
            placeholder: 'Select',
            minimumInputLength: 3,
            width: '100%',
            ajax: {
                url: '/Base/Search_Select2',
                type: 'post',
                dataType: 'json',
                delay: 250, // Increased the delay to prevent too many requests
                data: function (params) {
                    return {
                        prefix: params.term,
                        Params: selectElement.attr("Params"),
                        TargetID: selectElement.attr("TargetID"),
                        TableName: selectElement.attr("TableName")
                    };
                },
                processResults: function (data) {
                    return {
                        results: $.map(data, function (item) {
                            return { id: item.Id, text: item.Name };
                        })
                    };
                },
                cache: true
            },
            escapeMarkup: function (markup) { return markup; }
        });
    });
}

Finally , in case your reference of select2 might be incorrect, here is my _Layout configuration.

<!DOCTYPE html>
<html lang="en">
<head>
    …
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" />
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/Jquery2.styles.css" asp-append-version="true" />
</head>
<body>
…
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>

enter image description here enter image description here