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

DataTable中Select2无法加载,Controller的GetCompany方法未调用求助

问题排查与修复方案

核心问题分析

你的代码存在几个关键问题导致Select2无法加载且GetCompany方法未被调用:

  1. 重复HTML ID:所有渲染的<select>都使用相同的id="drpCompany",违反HTML唯一性规则,jQuery只会选择第一个匹配元素。
  2. 初始化时机错误:Select2初始化代码在DataTable异步加载数据前执行,此时<select>元素尚未生成。
  3. 重复初始化冲突:drawCallback中调用$("select").select2()会初始化无AJAX配置的基础Select2,后续单独的初始化代码因时机问题无法生效。
  4. DataTable参数拼写错误:datatype应为dataType(首字母大写),影响JSON响应解析。
  5. AJAX数据格式错误:Select2的data参数使用字符串'{}',正确格式应为函数或对象。

修正后的完整代码

$('#tblQuestion').DataTable({
    "ajax": {
        "url": "/FormQuestion/FormQuestion/GetQuestionListByFormId",
        "data": function (data) {
            data.formId = $("#formId").val();
        },
        "type": "POST",
        "dataType": "json" // 修正拼写错误
    },
    "columns": [
        {
            "render": function (data, type, row) {
                // 用类替代重复ID,确保HTML合法性
                return '<select class="drpCompany select" style="width:400px"></select>';
            },
        },
    ],
    drawCallback: function (settings) {
        // 仅初始化未被Select2处理过的下拉框,避免重复初始化
        $(".drpCompany").not('.select2-hidden-accessible').select2({
            minimumInputLength: 0,
            ajax: {
                cache: false,
                dataType: "json",
                type: "Post",
                url: "/Company/Company/GetCompany",
                data: function (params) {
                    // 可在此添加搜索参数,如:searchTerm: params.term
                    return {};
                },
                processResults: function (data) {
                    return {
                        results: $.map(data, function (item) {
                            console.log(item);
                            return {
                                text: item.name,
                                id: item.id
                            }
                        })
                    };
                }
            }
        }).on('change', function (e) {
            var selectedData = $(this).select2('data');
            // 若需每行单独存储选中ID,建议使用行内隐藏输入框替代全局ID
            $("#companyId_Selected").val(selectedData[0]?.id || '');
        });
    }
});

额外注意事项

  • 行级数据存储:如果需要为每行单独保存选中的公司ID,建议在每行添加带类名的隐藏输入框(如<input type="hidden" class="companyIdSelected">),然后在change事件中通过$(this).closest('tr').find('.companyIdSelected')定位到对应行的输入框。
  • 网络请求验证:打开浏览器开发者工具的网络标签,确认GetCompany请求是否发送,检查URL是否与Controller路由匹配。
  • 资源依赖:确保页面已正确引入Select2的CSS和JS文件,缺失资源会导致Select2无法渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:23:12