绑定下拉的初始/默认值(选择)名单

绑定下拉的初始/默认值(选择)名单

问题描述:

我有一个小问题与设置下拉的初始值。下面的code是视图模型的定义,并在的$(document)初始化。就绪。我有一个名为阵列 sourceMaterialTypes selectedSourceMaterialType 重新presenting该数组的选定值。我初始化视图模型从(ASP.Net MVC)模式和ViewBag值。

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 sourceMaterialTypes and a selectedSourceMaterialType representing the selected value of that array. I am initializing the view model with values from the (ASP.Net MVC) Model and 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.

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

这一切工作除了在原材料下拉列表中最初选择的值正常( selectedSourceMaterialType 正确绑定,所以当下拉选择改变其值正确更新,它是只是我有一个问题)初始选择,它总是在我看来,模型中的 sourceMaterialTypes 数组中的第一项。

This all works fine except for the initially selected value in the source materials dropdown (selectedSourceMaterialType is 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 sourceMaterialTypes array on my view model.

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

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

我猜你需要,而不是只通过标识整个对象在 selectedSourceMaterialType 观察到的功能 - >

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

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