ドロップダウンリストの初期値を設定する際に問題があります。以下のコードは、ビューモデルの定義と初期化を$(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"); });
});
});
以下は、ノックアウトバインド定義のドロップダウン(選択)リストの定義です。
<select id="SourceMaterialTypeId"
name="SourceMaterialTypeId"
data-bind="options: sourceMaterialTypes,
optionsText: 'Name',
optionsValue : 'Id',
value: selectedSourceMaterialType"></select>
これは、すべてが(selectedSourceMaterialType
が正しくバインドされているドロップダウン選択は、その値が正しく更新されて変更した場合ので、それは私が問題を抱えています唯一の最初の選択がある原料のドロップダウンリストで最初に選択した値を除いて正常に動作します)、これは常にビューモデルのsourceMaterialTypes
配列の最初の項目です。
最初に選択した値は、(サーバー側)モデルからselectedSourceMaterialType
ビューモデルプロパティの値として初期化される値にしたいと考えています。
これは正常に動作するはずです。 > selectedSourceMaterialType:ko.observable(@ Html.Raw(Json.Encode(Model.SourceMaterialType))) '私はそれが空のパラメータだと思っています。 – neebz
@nEEbzいいえ、空でない.... 'selectedSourceMaterialType:ko.observable({" Id ":"名前 ":"フルーツ "、"説明 ":"フレッシュフルーツ "、" MeasuredIn ":1、" MeasuredInValue最初の選択は、sourceMaterialTypesの最初の項目です。sourceMaterialTypes:ko.observableArray([{"Id":1、 "Name": "コーヒー豆 "、"説明 ":"生コーヒー豆 "、" MeasuredIn ":0、" MeasuredInValue ":0}、{" Id ":2、" Name ":" Fruit "、" Description ":" Fresh最初の選択は "Coffee Bean"です) –
私は、selectedSourceMaterialType observable関数内のオブジェクト全体ではなく、IDだけを渡す必要があると思います - > 'selectedSourceMaterialType:ko.observable(2)' – neebz