MVC中使用jQuery Select2下拉框无法设置文本的问题求助
MVC中使用Select2设置DropDownList文本时出现"Cannot read properties of undefined (reading 'text')"错误
问题详情
在MVC项目中通过@Html.DropDownList助手类生成下拉框,结合jQuery Select2插件使用时,无法正常设置下拉框文本。尝试用Select2的val方法搭配trigger('change')设置值时,抛出错误:
Cannot read properties of undefined (reading 'text')
相关代码(Index.cshtml)
@Html.DropDownList("ddl", ViewBag.classFieldList as SelectList, "Select class", new { @id = "ddl", @class = "form-control", @name = "ddl", @onchange = "Checkclassvalu(this)" }) <script> $(document).ready(function () { $('#ddl').select2({ // closeOnSelect: false, }); var ddlclassvalue = 'seventh'; alert('class is : ' + ddlclassvalue); var optionValue = $("#ddl option:contains('" + ddlclassvalue + "')").val(); $("#ddl").select2("val", optionValue).trigger('change'); }); </script>
错误截图

问题原因及解决办法
核心原因
option:contains匹配逻辑问题:该选择器是模糊匹配,可能匹配到多个选项,或者当目标文本对应的选项不存在时,optionValue会返回undefined,传递给Select2后触发错误。- Select2版本API兼容性:新版Select2(4.0+)已不再推荐使用
select2("val", value)的调用方式,且若传入未定义的值会直接抛出异常。
修正后的代码
$(document).ready(function () { $('#ddl').select2(); var ddlclassvalue = 'seventh'; // 精准匹配选项文本,避免模糊匹配的误判 var targetOption = $("#ddl option").filter(function() { return $(this).text().trim() === ddlclassvalue; }); if (targetOption.length > 0) { var optionValue = targetOption.val(); // 使用标准jQuery val方法结合trigger触发Select2更新 $("#ddl").val(optionValue).trigger('change'); } else { console.log("未找到对应选项:" + ddlclassvalue); } });
额外注意事项
- 确认后端传递的
ViewBag.classFieldList中确实包含文本为'seventh'的选项,检查SelectList数据是否正确生成。 - 优先使用jQuery原生
val()方法设置值,再通过trigger('change')通知Select2更新UI,这是新版Select2的标准用法。 - 避免使用
contains进行选项匹配,防止因文本部分匹配导致的取值错误。
内容的提问来源于stack exchange,提问作者Srikanth Reddy
相关产品推荐
相关产品推荐

