我已将我的选择定义如下
<select id="selProductType" data-bind="options: productType , value: editProductType , optionsText: 'Name'" />
下面是我的代码,用于填充我的视图模型中的选择
// Loading combobox with Product Types
$.getJSON("../RestService/Product/AllProductTypes",
function (allData) {
var mappedProductType = $.map(allData, function (item) {
console.log(item.Id + ' ' + item.Name);
return new productType(item);
});
self.productType(mappedProductType);
});
当我初始化页面时,我想将默认值设置为选择。所以我试过下面
self.editProductType(4);
但它给了我TypeErrror,说对象4没有方法ID。
如何去做。我也在stackoverflow中经历了类似的帖子,但没有运气。
Knockout JS binding initial/default value of dropdown (select) list
答案 0 :(得分:2)
如果您没有指定:
optionsValue: 'Id'
在data-bind中,此情况下的绑定值必须是productType数组中的对象。
您可以选择默认对象:
self.editProductType(self.productType()[2]);
什么是optionsValue?
与optionsText类似,您还可以传递一个名为optionsValue的附加参数,以指定应使用哪些对象的属性来设置KO生成的元素的value属性。您还可以指定JavaScript函数来确定此值。此函数将接收所选项作为其唯一参数,并应返回一个字符串以用于元素的value属性。
通常,您只想使用optionsValue作为确保在更新可用选项集时KO可以正确保留选择的方法。例如,如果您反复获取列表通过Ajax调用“car”对象,并希望确保所选择的汽车被保留,您可能需要将optionsValue设置为&#34; carId&#34;或者每个“汽车”对象具有的唯一标识符,否则KO不一定知道哪个先前的“汽车”对象对应于哪个“汽车”对象。
请参阅:http://knockoutjs.com/documentation/options-binding.html