当数据来自服务器时,Knockout.JS在选择标记中找不到值属性

时间:2014-08-12 12:31:40

标签: javascript ajax knockout.js

ajax请求select标记后,如果我绑定下拉列表,则不会读取value属性。但是当我绑定view model recognise中的下拉列表时,例如:

如果我像这样绑定模型

,它就可以了
var CostModel = function (data) {

var getCosts = getAllCosts.bind(this);
    getCosts();

var months = [{ ID: 1, Name: 'january' }, { ID: 2, Name: 'february' }, { ID: 3, Name: 'march' }, ];
this.months = ko.observableArray(months); //after this value is set by default with 'march'

}

但是如果我在ajax请求之后绑定模型,则来自months数组的所有名称的来源都被绑定,但默认情况下所选项目在此示例中不起作用value of 3

function getAllCosts() {
    var self = this;
    $.ajax({
        url: "/CostManageView/List",
        cache: false,
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            var months = [{ ID: 1, Name: 'january' }, { ID: 2, Name: 'february' }, { ID: 3, Name: 'march' }, ];

            self.months(ko.utils.arrayMap(months, function (month) {
                return new Month(month);
            }));
        }
    });
}

HTML

<select data-bind="options: $root.months,
                       optionsText: 'Name',
                       optionsValue: 'ID',
                       value: 3"></select>

1 个答案:

答案 0 :(得分:1)

在您的示例中,ajax调用将花费一些时间来执行(异步)。但是,绑定可能在调用完成之前应用。这导致以下结果:

  1. 选项绑定已解决
  2. 值'3'不是select控件中的选项,因为$ root.months尚未填充(调用尚未返回)
  3. 由于(2),select控件的值将重置为null / undefined(不完全确定哪一个)
  4. 您的调用返回并填充observableArray $ root.months。但是,到现在为止,该值为null / undefined,因此不会选择march。
  5. 试试这个:

    $.ajax({
        url: "/CostManageView/List",
        cache: false,
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            var months = [{ ID: 1, Name: 'january' }, { ID: 2, Name: 'february' }, { ID: 3, Name: 'march' }, ];
    
            self.months(ko.utils.arrayMap(months, function (month) {
                return new Month(month);
            }));
            self.selectedMonth(3);
        }
    });
    
    <select data-bind="options: $root.months,
                       optionsText: 'Name',
                       optionsValue: 'ID',
                       value: $root.selectedMonth"></select>
    

    如果可行,请尝试在月份加载后设置selectedMonth