如何实现支持自定义值显示的Kendo DropDownList?
解决Kendo DropDownList显示自定义值的问题
问题分析
核心问题是组件从Autocomplete切换回DropDownList后,自定义值因不在下拉数据源中无法显示;之前尝试的dataBound方案因重复触发事件和未配置字段导致显示异常。
可行方案
方案1:将自定义值加入数据源(支持下拉选择)
该方案会把自定义值临时添加到DropDownList的数据源中,既保证输入框显示,也能在下拉列表中找到它,同时避免事件循环。
- 修正HTML配置
补充dataTextField、dataValueField(指定数据源的显示字段和值字段),绑定初始化事件:
<input class="js-editable" id="PlacedBy" name="PlacedBy" data-bind="kendoDropDownList: { value: PlacedBy, optionLabel: '@General.OptionLabel_Select', dataSource: { transport: { read: {url: '/api/common/GetEnabledUsers', data: {text:''} } }, schema: { model: { fields: { text: { type: "string" }, value: { type: "string" } } } } }, dataTextField: 'text', dataValueField: 'value', valuePrimitive: true, init: onDropDownInit }" />
- 编写初始化处理函数
在组件初始化后,检查当前值是否存在于数据源,不存在则添加,避免重复触发事件:
function onDropDownInit(e) { var dropdown = e.sender; var currentValue = dropdown.value(); var dataSource = dropdown.dataSource; // 先拉取数据源数据,检查值是否存在 dataSource.fetch(function() { var data = this.data(); var valueExists = data.some(item => item.value === currentValue); if (!valueExists && currentValue) { // 添加自定义值到数据源 dataSource.add({ text: currentValue, value: currentValue }); // 刷新下拉列表 dropdown.refresh(); } }); }
方案2:仅在输入框显示自定义值(无需加入下拉)
如果不需要自定义值出现在下拉选项中,只需开启输入建议和值原语模式,即可让输入框直接显示自定义值:
<input class="js-editable" id="PlacedBy" name="PlacedBy" data-bind="kendoDropDownList: { value: PlacedBy, optionLabel: '@General.OptionLabel_Select', dataSource: { transport: { read: {url: '/api/common/GetEnabledUsers', data: {text:''} } } }, dataTextField: 'text', dataValueField: 'value', valuePrimitive: true, filter: 'contains', suggest: true, ignoreCase: true }" />
原方案失败原因
[object Object]错误:未配置dataTextField和dataValueField,DropDownList无法识别要显示的字段,直接输出对象。dataBound重复触发:调用dataSource.add()会再次触发dataBound事件,导致无限循环。
内容的提问来源于stack exchange,提问作者Utsav
相关产品推荐
相关产品推荐

