How to load Select2 in Partial View?
Asked Answered
S

3

1

I have a controller called ProcessController along with its View, in this view I call a PartialView as Modal and in it I need to load data into a Jquery Select2 control.

PartialView

@model App.ViewModels.UnidadeOrganizacionalViewModel
@{
    ViewData["Title"] = "Nova unidade organizacional";
}

<div class="modal-header">
    <h4 class="modal-title">@ViewData["Title"]</h4>
    <button type="button" class="close" data-dismiss="modal">
        <span aria-hidden="true">×</span><span class="sr-only">Fechar</span>
    </button>
</div>

<form asp-action="CreateUnidadeOrganizacional">
    <div class="modal-body">

        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="IdContratante" class="control-label"></label>
            <select id="slcContratante" asp-for="IdContratante" class="form-control"></select>
            <span asp-validation-for="IdContratante" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Nome" class="control-label"></label>
            <input asp-for="Nome" class="form-control" />
            <span asp-validation-for="Nome" class="text-danger"></span>
        </div>

        <div class="modal-footer" style="padding-right:0">
            <input type="submit" value="Salvar" class="btn btn-success" />
            <input type="button" class="btn btn-info" value="Fechar" data-dismiss="modal" />
        </div>
    </div>
</form>

<script src="~/lib/select2/js/select2.js"></script>
<script>
    $(document).ready(function () {

        $('#slcContratante').select2({

            placeholder: 'Informe o contratante',
            allowClear: true,
            closeOnSelect: true,
            tags: false,
            minimumInputLength: 0,
            language: {
                inputTooShort: function () { return ""; },
                noResults: function () {
                    return "Nenhum resultado encontrado";
                },
                searching: function () { return "Pesquisando..." }
            },
            ajax: {
                type: 'GET',
                url: '/get-contratante',
                contentType: 'application/json',
                dataType: 'json',
                data: function (params) {
                    var query = {
                        search: params.term
                    }
                    return query;
                },
                processResults: function (json) {

                    return { results: objThat.MapSelect2(json) };
                }
            }
        });
    });
</script>

When I select Select2 it should open a dropdown with the data obtained through the ajax method that makes a call in ProcessController

[Route("get-contratante")]
public async Task<JsonResult> GetContratante(string search)
{
    IEnumerable<ContratanteViewModel> lstContratanteViewModel = null;
    lstContratanteViewModel = _mapper.Map<IEnumerable<ContratanteViewModel>>(await _contratanteBLL.GetByNome(search));
    return new JsonResult(lstContratanteViewModel);
}

No Ajax request happens, I checked the console and it has no error message and the Select2 control is correct when called by JQuery.

I tested the same Select2 in ProcessController View and the data was loaded, but in PartialView nothing happens.

Where am i going wrong?

Seventy answered 31/8, 2019 at 21:59 Comment(5)
Do you open development tools using F12 in browser to check whether there are errors?Bernardina
Yes, I checked in development tools if there were any errors in console and had no message, checked if any requests were made in Network, nothing happened.Seventy
Could you try to put all js code out of partial view and put them in the parent view in @section Scripts{}?Bernardina
I'll try to do this to test if it will work, I had already put all the Select2 code inside @section Scripts {} and referenced the JQuery libraries before, but I didn't get to remove JQuery references in _Layout.cshtml. This may have caused conflict.Seventy
Oh,you mean you use above js code in @section Scripts{} in partial view?That will not work.refer to https://mcmap.net/q/88358/-including-javascript-at-bottom-of-page-from-partial-views I edit my answer.Bernardina
E
2

Give this inside script partial view

$( document ).ready(function() {
     $("select").select2();
});
Elburt answered 5/9, 2019 at 6:42 Comment(0)
S
1

I faced this problem, and this is how I solved it :

1- inside partial view:

<script>
    $("#dropDownID").select2({
        dropdownParent: $(".modal-content")
    });
</script>

2- remove any tabindex="-1" from modal divs

3- in CSS file add:

.select2-close-mask {
    z-index: 2099;
}

.select2-dropdown {
    z-index: 3051;
}

4- add this to scripts part or javascript file:

$(document).ready(function () {

    $.fn.modal.Constructor.prototype.enforceFocus = function () { };    
}
Salta answered 14/2, 2022 at 21:12 Comment(0)
B
0

I test your code and it seems that you do not refer to your jquery first.The simplest way is that remove the reference in _Layout.cshtml:

<environment include="Development">
    @*<script src="~/lib/jquery/dist/jquery.js"></script>*@remove this line
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
</environment>

And add your jquery reference to your partial view like

<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/select2/js/select2.js"></script>

You could pressing F12 to check whether there are errors for you js code in browser and add breakpoints to your action to see whether it is hit.

Update:

You could not use @section Scripts{} in partial view, they will not work at all since the doc has said that:

Sections defined in a page or view are available only in its immediate layout page. They cannot be referenced from partials, view components, or other parts of the view system.

You could move all of your js code from the partial view to the parent view where you call the partial view,there you could use @section Scripts{} successfully.

Bernardina answered 2/9, 2019 at 6:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.