0

When I call Model.destroy, it sends the proper requests to the server. However, I handle errors not so RESTful, I return a JSON with some appropriate information instead of throwing a http exception.

Now I want to be able to prevent the deletion of the model in the callbacks. For ex;

window.UserView = Backbone.View.extend({
    //Other stuff here.
    clearSuccess: function (model, response) {
        if (!response.Exception) {
            $(this.el).fadeOut('fast', function() {
                $(this).remove();
            });
        }
        else {
            //Can I cancel the destroy here?
        }
    },
    clearFailed: function (model, response) {
        alert("failed");
    }
});

These are the 2 callbacks that I sent to the model's success and error parameter on the destroy method. So where my comment is, I'd like to tell Backbone.js "nevermind, server said I cant delete, so keep the model". How do I do this?

Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

2 Answers2

0

The simplest thing is probably to return both a non-success HTTP status code (400-599) and a response body with a JSON document with application-level error details. See this thread for more on the HTTP status:

Using HTTP status codes to reflect success/failure of Web service request?

If you do this, backbone should automatically know that a failure status means the destroy did not succeed on the server, and I think it will do the right thing.

Community
  • 1
  • 1
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • The thing about that is I'm using asp.net mvc, I have no control of the content body I return :(. This guy tried to help me, so I turned to json content; http://stackoverflow.com/questions/6639931/asp-net-mvc-httpexception-message-not-shown-on-client/6640082#6640082 – Shawn Mclean Jul 11 '11 at 04:18
0

You have control of the content body with ASP.net MVC. Just set the Response.StatusCode property to the value you want to use, then return a JSON response or a Content response, or whatever.

Response.StatusCode = (int)HttpStatusCode.Conflict;
return Json( errorMessage );

Works just fine.

Brandon Roberson
  • 511
  • 1
  • 4
  • 5