I have an entity on the server called foo which has a list of bars assigned to it. I want to be able to remove a single bar from the foo.
I don’t however want to update client side and send down the entire foo because the foo is a big object so would be a lot of Json to send up every time if I’m just removing one bar from the foo.
I just want to send down the bar then remove it from the foo entity.
I have my class foo
public class Foo
{
public Foo()
{
Bars = new Collection<Bar>();
}
public ICollection<Bar> Bars { get; set; }
}
I’ve mapped the route
routes.MapHttpRoute(
name: "fooBarRoute",
routeTemplate: "api/foo/{fooId}/bar/{barId}",
defaults: new { controller = "Bar", action = "RemoveBarFromFoo" }
);
Sending down the request via javascript (coffeescript)
$.ajax(
url: api/foo/1/bar/1,
data: jsonData,
cache: false,
type: 'XXX',
....
I’m just not sure what route to use, I’ve tried PUT but it doesn’t like it and I’m probably doing it wrong. I’m not really sure what route I should be using in this situation.
public class BarController : ApiController
{
public void RemoveBarFromFoo(int fooId, Bar bar)
{
// get the foo from the db and then remove the bar from the list and save
}
}
My question: What route should I be using to achieve this goal? Or if I’m going about this the wrong way what should I be doing?
Thanks, Neil
The HTTP verb that you are using must be DELETE and the action name called
Deletein order to follow standard RESTful conventions. Also this action should not take a Bar object as parameter. Only thebarIdbecause that’s all that the client sends:and you call:
and now yuo could remove the action from your route definition because it is the HTTP verb that dictates which action should be invoked: