Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js REST URL with ASP.NET MVC 3

I have been looking into Backbone.js lately and i am now trying to hook it up with my server-side asp.net mvc 3.

This is when i discovered a issue. ASP.NET listens to different Actions, Ex: POST /Users/Create and not just POST /users/. Because of that, the Model.Save() method in backbone.js will not work.

How should we tackle this problem? Do i have to rewrite the Backbone.Sync?

like image 334
Anders Avatar asked Jun 07 '11 09:06

Anders


2 Answers

The answer is not to override Backbone.sync. You rarely would want to do this. Instead, you need only take advantage of the model's url property where you can assign a function which returns the url you want. For instance,

Forum = Backbone.Model.extend({

  url: function() {
    return this.isNew() ? '/Users/Create' : '/Users/' + this.get('id');
  }

});

where the url used for a model varies based upon whether the model is new. If I read your question correctly, this is all you need to do.

like image 62
Bill Eisenhauer Avatar answered Oct 20 '22 19:10

Bill Eisenhauer


You either have to tell ASP.NET MVC to route proper REST urls or fix Backbone.sync so it sends the GET/POST requests at the proper URLs.

Backbone works with REST not with RESTful URLs. There may be an OS implementation of Backbone.sync that matches your urls though.

Recommend URLs that play more nicely with Backbone:

GET     /forums              ->  index
GET     /forums/new          ->  new
POST    /forums              ->  create
GET     /forums/:forum       ->  show
GET     /forums/:forum/edit  ->  edit
PUT     /forums/:forum       ->  update
DELETE  /forums/:forum       ->  destroy
like image 20
Raynos Avatar answered Oct 20 '22 19:10

Raynos