【发布时间】:2011-10-02 16:51:02
【问题描述】:
我在设置下拉菜单的初始值时遇到了一个小问题。下面的代码是$(document).ready中的视图模型定义和初始化。我有一个名为sourceMaterialTypes 的数组和一个selectedSourceMaterialType 代表该数组的选定值。我正在使用(ASP.Net MVC)模型和 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 id="SourceMaterialTypeId"
name="SourceMaterialTypeId"
data-bind="options: sourceMaterialTypes,
optionsText: 'Name',
optionsValue : 'Id',
value: selectedSourceMaterialType"></select>
这一切都很好,除了源材料下拉列表中最初选择的值(selectedSourceMaterialType 绑定正确,所以当下拉选择更改时,它的值会正确更新,这只是我遇到问题的初始选择) ,它始终是我的视图模型上 sourceMaterialTypes 数组中的第一项。
我希望最初选择的值是从(服务器端)模型初始化为 selectedSourceMaterialType 视图模型属性的值。
【问题讨论】:
-
这应该可以正常工作;检查生成的 html 的源并查看从 >
selectedSourceMaterialType:ko.observable(@Html.Raw(Json.Encode(Model.SourceMaterialType)))呈现的内容我怀疑它是一个空参数。 -
@nEEbz no, not empty....
selectedSourceMaterialType : ko.observable({"Id":2,"Name":"Fruit","Description":"Fresh Fruit","MeasuredIn":1,"MeasuredInValue":1}),是渲染的内容,但是初始选择是 sourceMaterialTypes 中的第一项...。它渲染为sourceMaterialTypes : ko.observableArray([{"Id":1,"Name":"Coffee Bean","Description":"Raw coffee beans","MeasuredIn":0,"MeasuredInValue":0},{"Id":2,"Name":"Fruit","Description":"Fresh Fruit","MeasuredIn":1,"MeasuredInValue":1}]),(初始选择是“咖啡豆”) -
我猜你只需要在 selectedSourceMaterialType 可观察函数中传递 Id 而不是整个对象 ->
selectedSourceMaterialType: ko.observable(2) -
是的,使用 optionsValue: 'Id',它会期望 selectedSourceMaterialType 只是 Id。
-
@nEEbz 啊,当然,我的错。如果您想提供该答案作为答案,我将接受并投票。
标签: javascript asp.net-mvc knockout.js