KnockoutJS:使用ko.toJSON(this)时,初始值不会发布到服务器?

时间:2011-12-05 13:51:10

标签: forms post knockout.js

我已经定义了这个javascript viewmodel:

function PersonViewModel() {
    // Data members
    this.Name = ko.observable();
    this.Function_Id = ko.observable();
    this.SubFunction_Id = ko.observable();
    this.Functions = ko.observableArray();
    this.SubFunctions = ko.observableArray();

    // Whenever the Function changes, update the SubFunctions selection
    this.Function_Id.subscribe(function (id) {
        this.GetSubFunctions(id);
    }, this);

    // Functions to get data from server
    this.Init = function () {
        this.GetFunctions();
        this.Function_Id('@(Model.Function_Id)');
    };

    this.GetFunctions = function () {
        var vm = this;

        $.getJSON(
            '@Url.Action("GetFunctions", "Function")',
            function (data) {
                vm.Functions(data);
            }
        );
    };

    this.GetSubFunctions = function (Function_Id) {
        var vm = this;
        if (Function_Id != null) {
            $.getJSON(
                '@Url.Action("GetSubFunctions", "Function")',
                { Function_Id: Function_Id },
                function (data) {
                    vm.SubFunctions(data);
                }
            );
        }
        else {
            vm.SubFunction_Id(0);
            vm.SubFunctions([]);
        }
    };

    this.Save = function () {
        var PostData = ko.toJSON(this);

        var d = $.dump(PostData);
        alert(d);

        $.ajax({
            type: 'POST',
            url: '/Person/Save',
            data: PostData,
            contentType: 'application/json',
            success: function (data) {
                alert(data);
            }
        });
    };
}

$(document).ready(function () {
    var personViewModel = new PersonViewModel();
    personViewModel.Init();

    ko.applyBindings(personViewModel);
});

单击“提交”按钮时,将发布选择列表中的数据,但不会发布“Function_Id”。

当我在“功能”下拉列表中选择其他值并单击“提交”按钮时,“Function_Id”的值将正确发布。

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

这是因为javascript中此关键字的范围

this.Init = function () {
    this.GetFunctions(); // this === PersonViewModel.Init
    this.Function_Id('@(Model.Function_Id)'); // calls PersonViewModel.Init.Function_Id(...)
};

您应该将引用存储到PersonViewModel实例。

var self = this;
self.Init = function () {
    self.GetFunctions();
    self.Function_Id('@(Model.Function_Id)'); // calls PersonViewModel.Function_Id(...)
};