문제

The following java-script which defines the MyViewModel object with a property "text" and a function "save".

<script type="text/javascript">
    function MyViewModel() {
        this.text = ko.observable('');
    }

    MyViewModel.prototype.save = function () {
        alert(this.text()); // Works fine
        var data = ko.ToJSON(this); // Error: Object doesn't support this property or method ?
        $.ajax({
            type: 'POST',
            url: '/Person/Save',
            data: data,
            contentType: 'application/json',
            success: function (data) {
                alert(data);
            }
        });
    };
</script>

<script type="text/javascript">
    $(function () {
        var viewModel = new MyViewModel()
        ko.applyBindings(viewModel);
    });
</script>


And the following button defined:

<button data-bind="click: save">SAVE</button>


Result when the button is clicked:

  • Accessing a property using this.text() works fine
  • Converting the java-script object to a JSON object : ko.ToJSON(this) does not work and throws an error: "Error: Object doesn't support this property or method"

Probably something trivial is missing or wrong, but I can't see it. Any tips ?

도움이 되었습니까?

해결책

Knockout doesn't have a ToJSON method - it does have a toJSON method though:

function MyViewModel() {
    this.text = ko.observable('');
}

MyViewModel.prototype.save = function () {
    alert(this.text()); // Works fine
    var data = ko.toJSON(this); // Works fine too
    $.ajax({
        type: 'POST',
        url: '/Person/Save',
        data: data,
        dataType: 'json',
        success: function (data) {
            alert(data);
        }
    });
};

다른 팁

You have defined your view model as a function (a class, if you like):

function MyViewModel() {
    this.text = ko.observable('');
}

Instead, you should define it as a var (an object):

var MyViewModel = {
    text: ko.observable('');
}

You should then find that the following works fine:

var data = ko.ToJSON(MyViewModel);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top