0

我需要创建包含从 Json 对象接收到的数据的外部变量(数组)。该数据数组将用于绑定组合框。

我尝试过的:-

var data = [
    $.ajax({
        type: "POST",
        url: 'TimeRecord.aspx/ReturnComplexType',
        data: {},
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (arg) {
            alert('hello Inside new');
            for (var i = 0; i < arg.d.length ; i++) {
                "projectCode"=arg.d[i].ProjectCode
                //data.push(arg.d[i].ProjectCode)

            }

        },
        error: function (arg) {
        }
    })
];

HTML 代码:

  <td><select id="Select2" data-bind='options: data, value: selectedProject' style="width: 312px"></select>

我尝试了不同的方法在 for 循环中为这个 var 变量赋值。但我无法绑定它。请帮忙.....

编辑:我的完整其他代码

function ViewModel() {
    var self = this;
    this.CheckIn = ko.observable();
    this.CheckOut = ko.observable();
    this.Lunch = ko.observable();
    this.projectLine = ko.observableArray([new projectsWorked()]);

    this.TimeForWork = ko.computed(function () {
        return this.CheckIn() ? this.CheckOut() ? parseFloat(this.Lunch()) ? parseFloat(this.CheckOut()) - parseFloat(this.CheckIn()) - parseFloat(this.Lunch()) : parseFloat(this.CheckOut()) - parseFloat(this.CheckIn()) : 0 : 0;
    }, this);

    this.Rest = ko.observable();

    this.RemainHour = ko.computed(function () {
        return self.TimeForWork() ? self.Rest() ? self.WorkOnProject() ? parseFloat(self.TimeForWork()) - parseFloat(self.Rest()) - parseFloat(self.WorkOnProject()) : parseFloat(self.TimeForWork()) - parseFloat(self.Rest()) : parseFloat(self.TimeForWork()) : 0
    }, this);

    this.WorkOnProject = ko.observable();
    this.grandTotal = ko.observable();

    this.AddLine = function () {
        alert('hello Add');
       // alert(this.grandTotal());
        this.calcTotal();
        this.projectLine.push(new projectsWorked());
    };

    this.removeLine = function (line) {
        alert('hello Remove');
        self.projectLine.removeLine;      
    };
};

function projectsWorked() {
    var self = this;
    this.projectEnable = ko.observable(false); 
    this.hours = ko.observable();
    this.selectedProject = ko.observable();

};

ko.applyBindings(new ViewModel());
4

1 回答 1

1

您要填充的数据必须是 observableArray。获取数据后,您应该设置它。在你的ViewModel你可以有那个 observableArray 并且options标签必须绑定到它。您的代码应如下所示:

在您的 ViewModel 中类似于:

optionsData = ko.ObservableArray;
...
// later you should make your ajax call and fill optionsData observable

并且您的视图必须更改为绑定到 optionsData:

data-bind='options: optionsData

制作全局变量来进行这些绑定并不是一个好的解决方案。

于 2013-07-04T12:08:26.930 回答