Joe
Joe

Reputation: 1305

Put request on WebApi with collection

I'm working in an ASP.NET MVC 5 project w/ WebApi and Knockout.js, and I'm trying to replace a collection when saving on a page. First, for something simple that does work in my WebApiController, updating one item:

public IHttpActionResult Put(FooObject obj, CancellationToken cancellationToken) {
  // obj is of type FooObject and has the goods I need
  ...
}

However, this doesn't work:

public IHttpActionResult Put(IEnumerable<FooObject> listOfObj, CancellationToken cancellationToken) {
  // nope; listOfObj is empty, including trying List<> instead of IEnumerable<>
  ...
}

And here's my relevant JS code:

draggable_service.prototype.update = function (data) {
   var self = this;
   return $.ajax({
      data: data,
      type: "PUT",
      url: self.url
   });
};
...

var draggableService = new draggable_service(service_url);
...
function submitChanges() {
    draggableService.update(vm.addedItems());
}
...

My instinct is that I'm missing something basic w/ the WebApi stuff, but I'm not sure what that is. Any thoughts?

Upvotes: 0

Views: 154

Answers (1)

Gabe
Gabe

Reputation: 462

I think you have to mark your collection parameter with the frombody attribute

public IHttpActionResult Put([FromBody]IEnumerable<FooObject> listOfObj, CancellationToken cancellationToken) {
  // nope; listOfObj is empty, including trying List<> instead of IEnumerable<>
  ...
}

as i recal your data for the ajax call should be in the following format :

draggable_service.prototype.update = function (data) {
   var self = this;
   return $.ajax({
      data: {'': data},
      type: "PUT",
      url: self.url
   });
};

Upvotes: 1

Related Questions