[英]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.