Reputation: 865
I am not able to post data collection from knockout to my webapi service.
My knockout code:
$.ajax("/api/tasks/PostTask", {
data: ko.toJSON({ tasks: self.tasks }),
type: "post", contentType: "application/json",
success: function (result) { alert(result) }
});
};
if i put the output of ko.toJSON({ tasks: self.tasks }) to a div tag the result is:
{"tasks":[{"title":"task# 0","isDone":false},{"title":"task# 1","isDone":false},{"title":"task# 2","isDone":false},{"title":"task# 3","isDone":false},{"title":"task# 4","isDone":false},{"title":"task# 5","isDone":false}]}
so, iam sending data.
My webapi method:
public void PostTaskCollection(List<Task> tasks)
{
foreach (Task item in tasks)
{
string _title = item.title;
}
}
when i put a breakpoint in, i see that the tasks variable is null. What am i doing wrong? Why doesn't the collection get passed to my webapi method?
Upvotes: 4
Views: 261
Reputation: 139758
You don't need to wrap your self.tasks
in a new object otherwise Web.Api won't bind correctly because of the "tasks"
prefix. So just write ko.toJSON(self.tasks)
.
So this call should work:
$.ajax("/api/tasks/PostTask", {
data: ko.toJSON(self.tasks),
type: "post",
contentType: "application/json",
success: function (result) { alert(result); }
});
Upvotes: 2