[英]Binding initial/default value of dropdown (select) list
我在设置下拉列表的初始值时遇到了一个小问题。 下面的代码是视图模型定义和$(document).ready
的初始化。 我有一个数组称为sourceMaterialTypes
和selectedSourceMaterialType
表示阵列的所选择的值。 我正在使用(ASP.Net MVC)Model和ViewBag中的值初始化视图模型。
var viewModel = {
sourceMaterialTypes :
ko.observableArray(@Html.Raw(Json.Encode(ViewBag.SourceMaterialTypes))),
selectedSourceMaterialType :
ko.observable(@Html.Raw(Json.Encode(Model.SourceMaterialType))),
ingredientTypes :
ko.observableArray(@Html.Raw(Json.Encode(ViewBag.IngredientTypes))),
selectedIngredientType : ko.observable()
};
$(document).ready(function () {
ko.applyBindings(viewModel);
viewModel.selectedSourceMaterialType.subscribe(function(newSourceMaterialType) {
$.getJSON("/IngredientType/FindByMaterialType",
{ "id": newSourceMaterialType })
.success(function (data) {
viewModel.ingredientTypes($.parseJSON(data));
})
.error(function () { alert("error"); });
});
});
以下是具有Knockout绑定定义的下拉列表(select)列表的定义。
<select id="SourceMaterialTypeId"
name="SourceMaterialTypeId"
data-bind="options: sourceMaterialTypes,
optionsText: 'Name',
optionsValue : 'Id',
value: selectedSourceMaterialType"></select>
这一切都正常,除了源材料下拉列表中最初选择的值( selectedSourceMaterialType
被正确绑定,因此当下拉选择更改其值正确更新时,它只是我遇到问题的初始选择),这始终是我的视图模型上的sourceMaterialTypes
数组中的第一项。
我希望最初选择的值是从(服务器端)模型初始化的值,作为selectedSourceMaterialType
视图模型属性的值。
我想你需要传递Id而不是传递selectedSourceMaterialType
可观察函数中的整个对象 - >
selectedSourceMaterialType: ko.observable(@Model.SourceMaterialType.Id)
API为您提供了解决方案,您只需要在您的选择中添加optionsCaption。
<select id="SourceMaterialTypeId"
name="SourceMaterialTypeId"
data-bind="options: sourceMaterialTypes,
optionsText: 'Name',
optionsValue : 'Id',
value: selectedSourceMaterialType,
optionsCaption: 'Please select...'"></select>
正如@nEEBz建议的那样, selectedSourceMaterialType
初始化不正确。 在learn.knockoutjs.com“列表和集合”教程中 ,他们通过传递可观察数组的特定索引的值来初始化其viewmodel的selected-item属性。 例如,执行以下操作:
selectedSourceMaterialType: ko.observable(sourceMaterialTypes[2])
......而不是这个:
selectedSourceMaterialType: ko.observable({"Id":1,"Name":"Coffee Bean" /* ... */});
这样,所选项的值是对下拉列表项所来自的同一可观察数组中的项的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.