簡體   English   中英

綁定下拉列表(選擇)列表的初始/默認值

[英]Binding initial/default value of dropdown (select) list

我在設置下拉列表的初始值時遇到了一個小問題。 下面的代碼是視圖模型定義和$(document).ready的初始化。 我有一個數組稱為sourceMaterialTypesselectedSourceMaterialType表示陣列的所選擇的值。 我正在使用(ASP.Net MVC)Mod​​el和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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM