Reputation: 10037
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?
Upvotes: 3
Views: 2460
Reputation: 22652
Following is not a direct answer - but some useful links for using Knockout with Web API (though I have not tried development with knockout yet, the articles are informative)
Upvotes: 0
Reputation: 10037
It turn out I need to rename my class.
public class RootObject
{
public List<QuickEntry> quickEntries { get; set; }
}
public class QuickEntry
{
public string ItemPartNumb { get; set; }
public string ItemDescription { get; set; }
public string ItemQuanties { get; set; }
}
Upvotes: 0
Reputation: 7738
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);
Upvotes: 2