绑定下拉列表(选择)列表的初始/默认值

Sim*_*Fox 34 javascript asp.net-mvc knockout.js

我在设置下拉列表的初始值时遇到了一个小问题.下面的代码是视图模型定义和初始化$(document).ready.我有一个名为sourceMaterialTypesa 的数组,selectedSourceMaterialType表示该数组的选定值.我正在使用(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"); });
    });
});
Run Code Online (Sandbox Code Playgroud)

以下是具有Knockout绑定定义的下拉列表(select)列表的定义.

<select id="SourceMaterialTypeId"
        name="SourceMaterialTypeId"
        data-bind="options: sourceMaterialTypes,
                   optionsText: 'Name',
                   optionsValue : 'Id',
                   value: selectedSourceMaterialType"></select>
Run Code Online (Sandbox Code Playgroud)

这一切都正常,除了源材料下拉列表中最初选择的值(selectedSourceMaterialType正确绑定所以当下拉选择更改其值正确更新时,它只是我遇到问题的初始选择),这始终是第一个sourceMaterialTypes我视图模型中数组中的项.

我希望最初选择的值是从(服务器端)模型初始化的值作为selectedSourceMaterialType视图模型属性的值.

nee*_*ebz 13

我猜你只需要传递Id而不是整个对象在selectedSourceMaterialType可观察函数中 - >

selectedSourceMaterialType: ko.observable(@Model.SourceMaterialType.Id)
Run Code Online (Sandbox Code Playgroud)

  • 但是,如果你想提供整个对象而不使用optionsValue:'Id',有没有人知道怎么做? (12认同)

小智 5

API为您提供了解决方案,您只需要在您的选择中添加optionsCaption.

<select id="SourceMaterialTypeId"
    name="SourceMaterialTypeId"
    data-bind="options: sourceMaterialTypes,
               optionsText: 'Name',
               optionsValue : 'Id',
               value: selectedSourceMaterialType,
               optionsCaption: 'Please select...'"></select>
Run Code Online (Sandbox Code Playgroud)

  • 我认为问题更侧重于将初始/默认值设置为模型/视图模型设置的值.因此,如果在编辑项目时,您希望显示最后选择的值,而不是"请选择..." (11认同)