我在设置下拉菜单的初始值时遇到了一个小问题。下面的代码是$(document).ready
中的 View 模型定义和初始化。我有一个名为 sourceMaterialTypes
的数组和一个代表该数组的选定值的 selectedSourceMaterialType
。我正在使用 (ASP.Net MVC) 模型和 ViewBag 的值初始化 View 模型。
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 绑定(bind)定义的定义。
<select id="SourceMaterialTypeId"
name="SourceMaterialTypeId"
data-bind="options: sourceMaterialTypes,
optionsText: 'Name',
optionsValue : 'Id',
value: selectedSourceMaterialType"></select>
这一切都很好,除了源 Material 下拉列表中最初选择的值(selectedSourceMaterialType
被正确绑定(bind),所以当下拉选择更改时,它的值被正确更新,这只是我的初始选择遇到问题),这始终是我 View 模型上 sourceMaterialTypes
数组中的第一项。
我希望最初选择的值是从(服务器端)模型初始化为 selectedSourceMaterialType
View 模型属性的值。
最佳答案
我想您只需要传递 Id 而不是 selectedSourceMaterialType
可观察函数中的整个对象 ->
selectedSourceMaterialType: ko.observable(@Model.SourceMaterialType.Id)
关于javascript - 绑定(bind)下拉(选择)列表的初始/默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6648991/