Reputation: 9830
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:
Probably something trivial is missing or wrong, but I can't see it. Any tips ?
Upvotes: 2
Views: 11434
Reputation: 159955
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);
}
});
};
Upvotes: 4
Reputation: 13278
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);
Upvotes: 0