我有一个从对引用数据服务的 ajax 调用返回的状态列表
我在我的 js 文件中定义了这个:
self.StatusIdList = ko.observableArray();
self.StatusTextList = ko.observableArray();
这是我的 ajax 调用的成功处理程序:
success: function (data, textStatus, message) {
$.each(data, function (index, item) {
self.StatusTextList.push(item.statusDescription);
self.StatusIdList.push(item.statusId);
});
},
这就是我的 HTML 中的内容
<select data-bind="options: StatusIdList, value: currentFormStatus, optionsText: StatusTextList" class="span12"></select>
如果我将选项设置为 StatusTextList,则下拉列表将按预期填充状态列表 - 但是将其设置为 ID 时,它会填充我不想要的 id 列表。
因此,我尝试使用 optionsText,并希望它会在下拉列表中显示名称,但将每个状态的唯一 ID 保留在选项值中,但在下拉列表中,我当前的代码如上所示,显示如下:
<option value="1">[object Window]</option>
实际上,statusId = 1 的唯一 ID 应显示为“订单已收到”
最佳答案
您不需要 2 个单独的数组来填充下拉列表。创建一个名为 StatusList
的 observableArray
,其中的项目同时具有 statusId
和 statusDescription
属性。 (more on options
binding from KO website)
在 HTML 中:
<select data-bind="options: StatusList, value: currentFormStatus, optionsText: 'statusDescription', optionsValue: 'statusId', optionsCaption: 'Select'"></select>
optionsText
应指向数组中您希望在下拉列表中显示为文本的任何属性。在我们的例子中,它是statusDescription
。
optionsValue
应指向作为选项值的属性。在本例中,它是 statusId
。
var viewModel = function (data) {
var self = this;
self.currentFormStatus = ko.observable();
self.StatusList = ko.observableArray([]);
// functions, ajax etc
};
在您的成功回调中:
// you can push to the array in your callback like this
// each item in "data" should have "statusDescription" and "statusId" properties
success: function (data, textStatus, message) {
$.each(data, function (index, item) {
self.StatusList.push(item);
});
},
我创建了一个fiddle
关于javascript - 通过 knockout 绑定(bind)到下拉菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46092175/