相关疑难解决方法(0)

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

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

javascript asp.net-mvc knockout.js

34
推荐指数
2
解决办法
5万
查看次数

标签 统计

asp.net-mvc ×1

javascript ×1

knockout.js ×1