You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP .Net Core中通过代码为Select2 jQuery设置值

解决Select2 AJAX模式下动态设置默认选中项的问题

问题分析

你当前的代码里,直接用$('#User').val(userId).trigger('change')无效,核心原因是Select2在AJAX模式下,未通过搜索加载的选项并不存在于DOM中,Select2无法识别一个仅存在ID但没有对应文本的选项,所以直接赋值ID不会触发选中效果。另外你的代码里还有个笔误:设置Employee选中时,错误地操作了#User元素,这也会导致Employee的选中逻辑完全失效。

可行解决方案

方案1:手动构造选项并触发Select2选中事件

不需要提前添加DOM选项,直接通过Select2的API构造选中项对象,触发select2:select事件来完成选中:

修改你的脚本部分:

$(document).ready(function () {
    $('select').each(function () {
        InitSelect2(this.id);
    });

    // 设置User选中项
    if(userId){
        // 先通过AJAX获取该ID对应的文本(可选,避免选中后显示空白)
        $.post($('#User').data('url'), { id: userId }, function(data) {
            if(data.results && data.results.length > 0) {
                var userOption = data.results[0];
                $('#User').append(new Option(userOption.text, userOption.id, true, true)).trigger('change');
            }
        }, 'json');
    }

    // 设置Employee选中项(修正选择器)
    if(emplyeeId){
        $.post($('#Employee').data('url'), { id: emplyeeId }, function(data) {
            if(data.results && data.results.length > 0) {
                var empOption = data.results[0];
                $('#Employee').append(new Option(empOption.text, empOption.id, true, true)).trigger('change');
            }
        }, 'json');
    }
});

这种方式的原理是先给Select2添加对应ID的option元素,再通过trigger('change')通知Select2更新选中状态,同时通过AJAX获取文本保证显示正常。

方案2:在Select2初始化时加载并设置选中项

修改你的InitSelect2函数,支持在初始化时传入选中ID,直接通过AJAX获取该选项的数据并设置为选中:

function InitSelect2(selector, selectedId = 0) {
    var $select = $("#" + selector);
    var url = $select.data('url');
    var placeholder = $select.data('placeholder');
    const type = "POST";
    const dataType = "json";
    if (!url) {
        console.error("Selector: " + selector + " Unspecified URL");
        return;
    }
    if (placeholder === "") {
        console.error("Selector: " + selector + " Unspecified Placeholder");
        return;
    }
    try {
        $select.select2({
            theme: "bootstrap-5",
            width: $select.data('width') ? $select.data('width') : $select.hasClass('w-100') ? '100%' : 'style',
            placeholder: placeholder,
            allowClear: true,
            minimumInputLength: 3,
            ajax: {
                url: url,
                type: type,
                dataType: dataType,
                delay: 250,
                data: function (params) {
                    var query = {
                        id: selectedId,
                        searchFullName: params.term,
                    }
                    return query;
                },
                processResults: function (data) {
                    return {
                        results: data.results
                    };
                },
            }
        });

        // 如果有选中ID,初始化后获取该选项数据并设置
        if (selectedId > 0) {
            $.ajax({
                url: url,
                type: type,
                dataType: dataType,
                data: { id: selectedId, searchFullName: '' },
                success: function(data) {
                    if(data.results && data.results.length > 0) {
                        var option = data.results[0];
                        $select.append(new Option(option.text, option.id, true, true)).trigger('change');
                    }
                }
            });
        }
    } catch (ex) {
        console.error(ex);
    }
}

然后在初始化的时候直接传入选中ID:

$(document).ready(function () {
    // 初始化时传入对应的选中ID
    InitSelect2('User', userId);
    InitSelect2('Employee', emplyeeId);
});

这种方式的优势是初始化Select2的同时自动加载选中项的数据,逻辑更统一,不需要额外的代码处理选中逻辑。

关键注意事项

  • 修正代码中的笔误:设置Employee选中时,必须操作#Employee元素,而不是#User。
  • 确保你的后端接口支持通过id参数单独返回对应选项的数据,这样才能获取到选中项的文本信息。
  • 两种方案都依赖后端接口能根据ID返回单个选项的结果,否则无法正确显示选中文本。

内容的提问来源于stack exchange,提问作者makaMa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 23:25:37