Code for Coffee Logo

Binding parameters to Web API controller with Backbone.js

Posted on Jun 24, 2014

This is a really quick write-up of an issue that isn’t well documented. One of our work related projects uses Backbone.js on the front end to handle models and collections and is powered by ASP.NET Web API 2.0. I ran into an issue regarding using the built in model functions .save() and .fetch().

I found that to pass parameters in (either from a model or somewhere else) when making a GET request (such as the model.fetch() method) to the controller, you needed to declare the model/parameter with the [FromUri] attribute. Example:

public testSampleModel Get([FromUri]testSampleModel  model) { ... }

How to send in a parameter on a .fetch()? Good question - here’s the answer (using jQuery):

myModel.fetch({ data: $.param({ paramName: "foobar"}) });

To pass parameters/model when making a POST request (such as model.save()), I found that you must declare the model/parameter as either [FromBody] or without an attribute at all. Example:

public testSampleModel Get([FromBody]testSampleModel  model) { ... }

That’s it - just a quick, informative post.

Comments