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?

Renan Barbosa
  • 1,046
  • 3
  • 11
  • 31
  • Do you open development tools using F12 in browser to check whether there are errors? – Ryan Sep 02 '19 at 05:23
  • 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. – Renan Barbosa Sep 02 '19 at 09:18
  • Could you try to put all js code out of partial view and put them in the parent view in @section Scripts{}? – Ryan Sep 02 '19 at 09:35
  • 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. – Renan Barbosa Sep 02 '19 at 11:09
  • Oh,you mean you use above js code in @section Scripts{} in partial view?That will not work.refer to https://stackoverflow.com/a/48769045/10158551 I edit my answer. – Ryan Sep 03 '19 at 01:24

3 Answers3

2

Give this inside script partial view

$( document ).ready(function() {
     $("select").select2();
});
Nijin P J
  • 1,302
  • 1
  • 9
  • 15
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 () { };    
}
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.

Ryan
  • 19,118
  • 10
  • 37
  • 53