I didn't find much info on web api post. Here is one blog entry that I find that talk about how to do POST from knockout. Web Api POST with KnockoutJs ViewModel
ViewModel :
<script type="text/javascript">
var QuickEntry = function (_itemPartNumb, _itemDescription, _itemQuanities) {
this.ItemPartNumb = ko.observable(_itemPartNumb);
this.ItemDescription = ko.observable(_itemDescription);
this.ItemQuanties = ko.observable(_itemQuanities);
};
function QuickEntriesViewModel() {
var self = this;
self.quickEntries = ko.observableArray([]);
for (var i = 0; i < 10; i++) {
self.quickEntries.push(new QuickEntry());
}
self.addNewRow = function () {
self.quickEntries.push(new QuickEntry());
}.bind(self);
self.addToCart = function() {
var items = ko.toJSON(self);
$.ajax({
url: '/DesktopModules/blah/API/Data/Post',
type: 'POST',
data: items,
datatype: "json",
processData: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
statusCode: {
404: function () {
alert('Failed');
}
}
});
};
};
ko.applyBindings(new QuickEntriesViewModel());
DataController (Web Api)
[HttpPost]
public string Post(quickEntries values)
{
string response = string.Empty;
response = values.Items != null ? "some data" : "nothing at all";
return response;
}
//class
public class quickEntries
{
public MyQuickEntry[] Items { get; set; }
}
public class MyQuickEntry
{
public string ItemPartNumb { get; set; }
public string ItemDescription { get; set; }
public string ItemQuanties { get; set; }
}
This is what is passing to web api POST method from fiddler:
{"quickEntries":[{"ItemPartNumb":"bob","ItemDescription":"bob","ItemQuanties":"bob"},{},{},{},{},{},{},{},{},{}]}
Does anyone have experience with passing a array of json objects to web api?
The problem is you are sending the ViewModel, not the array of objects:
var items = ko.toJSON(self);
This turns the entire ViewModel object into JSON. Try converting just the array:
var items = ko.toJSON(self.quickEntries);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With