Reputation: 877
I followed the http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/ article to submit data using ko.utils.postJson and navigate to a different view from the controller
I used ko.utils.postJson(location.href, {model: ko.toJson(viewModel)});
to submit the data but the model submitted to the server has empty properties.
ko.utils.postJson(location.href, {model: viewModel});
failed too.
The client viewModel has additional properties than the server model but I believe if it works with $ajax post method, it should work with KO post
It worked if I pass the model as under
ko.utils.postJson(location.href,
{model: {P1:this.p1(), P2:this.p2(), P3: this.p3()}});
Do I have to map each property before submission? Its also really confusing when to use () for viewModel properties
Server Code
[HttpPost]
public ActionResult SearchProperty([FromJson]MyModel model)
{
try
{
return View("XYZ", model);
}
catch (Exception e)
{
}
}
Upvotes: 3
Views: 4237
Reputation: 114792
Knockout provides a utility function that will turn an object containing observables into a plain JavaScript object. The utility function is ko.toJS
. So, if you did:
{ model: ko.toJS(viewModel) }
Then, it would handle unwrapping all of your observables.
Additionally, there is another function ko.toJSON
that will do a ko.toJS
and then do JSON.stringify
on the result. This is useful when you really need JSON instead of a JavaScript object.
Upvotes: 5