I am stucked on this problem since yesterday. I start learning knockoutjs with ASP.Net WebAPI. Everything work very well until i post the data back to the API Controller. everytime I paseed the data to the controller it shows null value for every field of the Person object.
I tried everything e.g. using $.ajax with contentType: 'application/json', or contentType: 'application/json, utf-8...' but nothing works for me. please give some solution i will be very thankful to you..
here is the code of WebAPI Post Method:
// POST api/some
public HttpResponseMessage Post([FromBody]Person value)
{
repository.SavePerson(value);
return Request.CreateResponse(HttpStatusCode.OK);
}
And here is Person class
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public List<string> activities { get; set; }
public string favoriteHobby { get; set; }
}
And here is javascript / knockout code
function PersonViewModel() {
var self = this;
self.firstName = ko.observable('');
self.lastName = ko.observable('');
self.activities = ko.observableArray([]);
self.favoriteHobby = ko.observable('');
self.loadUserData = function () {
$.getJSON("api/Some/Get", function (data) {
self.firstName(data.firstName);
self.lastName(data.lastName);
self.activities(data.activities);
self.favoriteHobby(data.favoriteHobby);
});
}
self.saveUserData = function () {
var data_to_send = { value: ko.toJSON(self) };
$.post("api/Some/Post", data_to_send, function (data) {
});
}
};
ko.applyBindings(new PersonViewModel());
And finally here is the HTML
<form action="#" method="post">
<p>
First name:
<input data-bind='value: firstName' />
</p>
<p>
Last name:
<input data-bind='value: lastName' />
</p>
<div>
Your favorite food:
<select data-bind='options: activities, value: favoriteHobby'>
</select>
</div>
<p>
<button data-bind='click: loadUserData'>Load Data</button>
<button data-bind='click: saveUserData'>Save Data</button>
</p>
</form>
var data_to_send = ko.toJSON(self)
– Major Byte