KnockoutJS : initial values are not posted to serv

2019-09-09 01:08发布

问题:

I've this javascript viewmodel defined:

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);
});

When the Submit button is clicked, the data from the select lists is posted, but NOT the 'Function_Id'.

When I choose a different value in the Function dropdown list, and the click the Submit button, the value for 'Function_Id' is correctly posted.

How to fix this ?

回答1:

It's because the scope of the this keyword in javascript

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

You should store the refrence to the PersonViewModel instance.

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