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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6648991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:37:06  来源:igfitidea点击:

Binding initial/default value of dropdown (select) list

javascriptasp.net-mvcknockout.js

提问by Simon Fox

I'm having a small issue with setting the initial value of a dropdown. The code below is the view model definition and the initialization in $(document).ready. I have an array called sourceMaterialTypesand a selectedSourceMaterialTyperepresenting the selected value of that array. I am initializing the view model with values from the (ASP.Net MVC) Model and ViewBag.

我在设置下拉列表的初始值时遇到了一个小问题。下面的代码是视图模型定义和$(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"); });
    });
});

The following is the definition of my dropdown (select) list with the Knockout binding definition.

以下是我的下拉(选择)列表与 Knockout 绑定定义的定义。

<select id="SourceMaterialTypeId"
        name="SourceMaterialTypeId"
        data-bind="options: sourceMaterialTypes,
                   optionsText: 'Name',
                   optionsValue : 'Id',
                   value: selectedSourceMaterialType"></select>

This all works fine except for the initially selected value in the source materials dropdown (selectedSourceMaterialTypeis bound correctly so when the dropdown selection changes its value is correctly updated, it is only the initial selection I am having a problem with), which is always the first item in the sourceMaterialTypesarray on my view model.

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

I would like the initially selected value to be that which is initialized from the (server-side) model as the value of selectedSourceMaterialTypeview model property.

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

采纳答案by neebz

I guess you need to pass the Id only and not the whole object in the selectedSourceMaterialTypeobservable function ->

我想您只需要传递 Id 而不是selectedSourceMaterialType可观察函数中的整个对象->

selectedSourceMaterialType: ko.observable(@Model.SourceMaterialType.Id)

回答by Straith

The API has the solution for you, you'll just need to add optionsCaption to your select.

API 为您提供了解决方案,您只需将 optionsCaption 添加到您的选择中即可。

<select id="SourceMaterialTypeId"
    name="SourceMaterialTypeId"
    data-bind="options: sourceMaterialTypes,
               optionsText: 'Name',
               optionsValue : 'Id',
               value: selectedSourceMaterialType,
               optionsCaption: 'Please select...'"></select>

回答by Bryan

As @nEEBz suggested, selectedSourceMaterialTypeis initialized improperly. In the learn.knockoutjs.com "Lists and Collections" tutorial, they initialize their viewmodel's selected-item property by passing the value of a specific index of the observable array. For example, do this:

正如@nEEBz 建议的那样,selectedSourceMaterialType初始化不正确。在learn.knockoutjs.com “列表和集合”教程中,他们通过传递可观察数组的特定索引的值来初始化其视图模型的 selected-item 属性。例如,执行以下操作:

selectedSourceMaterialType: ko.observable(sourceMaterialTypes[2])

...instead of this:

...而不是这个:

selectedSourceMaterialType: ko.observable({"Id":1,"Name":"Coffee Bean" /* ... */});

That way, the value of the selected item is a reference to the item in the same observable array that the dropdownlist items come from.

这样,所选项目的值是对下拉列表项目来自的同一 observable 数组中项目的引用。