【问题标题】:How to load Select2 in Partial View?如何在局部视图中加载 Select2?
【发布时间】:2020-01-04 14:24:28
【问题描述】:

我有一个名为 ProcessController 的控制器及其视图,在此视图中,我将 PartialView 称为模态视图,在其中我需要将数据加载到 Jquery Select2 控件中。

部分视图

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

当我选择 Select2 时,它应该打开一个下拉列表,其中包含通过在 ProcessController 中调用的 ajax 方法获得的数据

[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);
}

没有发生 Ajax 请求,我检查了控制台,它没有错误消息,并且当被 JQuery 调用时,Select2 控件是正确的。

我在 ProcessController View 中测试了相同的 Select2 并加载了数据,但在 PartialView 中没有任何反应。

我哪里错了?

【问题讨论】:

  • 你是否在浏览器中使用F12打开开发工具检查是否有错误?
  • 是的,我在开发工具中检查了控制台是否有任何错误并且没有消息,检查了网络中是否有任何请求,没有任何反应。
  • 能否尝试将所有 js 代码从部分视图中移出,并将它们放在 @section Scripts{} 中的父视图中?
  • 我会尝试这样做以测试它是否可以工作,我已经将所有 Select2 代码放在 @section Scripts {} 中并之前引用了 JQuery 库,但我没有得到删除 _Layout.cshtml 中的 JQuery 引用。这可能导致了冲突。
  • 哦,你的意思是你在部分视图中使用@section Scripts{} 中的上述js 代码?那不行。参考stackoverflow.com/a/48769045/10158551 我编辑我的答案。

标签: jquery asp.net-core jquery-select2


【解决方案1】:

我测试了你的代码,看来你没有先引用你的jquery。最简单的方法是删除_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>

并将您的 jquery 引用添加到您的部分视图中,例如

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

您可以按 F12 来检查浏览器中的 js 代码是否有错误,并在您的操作中添加断点以查看它是否被命中。

更新:

您不能在部分视图中使用@section Scripts{},因为doc 说过,它们根本不起作用:

页面或视图中定义的部分仅在其直接布局页面中可用。它们不能被局部视图、视图组件或视图系统的其他部分引用。

您可以将所有 js 代码从局部视图移动到调用局部视图的父视图,在那里您可以成功使用@section Scripts{}。

【讨论】:

    【解决方案2】:

    给这个内部脚本partial view

    $( document ).ready(function() {
         $("select").select2();
    });

    【讨论】:

      猜你喜欢
      • 2011-11-09
      • 2017-09-01
      • 1970-01-01
      • 2020-11-07
      • 2012-11-10
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多