21

I call save using this:

console.log(this.model.isNew());
console.log(this.model);

this.model.save({}, {
    success: function (model, response, options) {
        console.log(response);
    },
    error: function (model, xhr, options) {
        console.log(xhr.result.Errors);
    }   
});

The isNew() returns false. But the output of this.model has an ID of 0. (this.model.id is 0 as well)

My url is url: ROOTAREA + "/Expenses/Entry/",

Updating works fine, and uses PUT as expected.

Edit : here's part of my model:

   defaults: function () {
        return {
            DocumentDate: "",
            JobNo_: "",
            PhaseCode: "",
            WorkTypeCode: "",
            Description: "",
            Quantity: 0,
            UnitCost: 0,
            ExpenseCurrencyCode: "",
            ReimbursementCurrencyCode: "",
            UnitofMeasureCode: "DIEM",
            LineNo_: 0
        };
    },
    idAttribute: "LineNo_",
D'Arcy Rail-Ip
  • 11,505
  • 11
  • 42
  • 67

3 Answers3

28

ID should not even exist for a new entry. The issue is in the part you didn't show - in the part where you instantiate, create and populate the model.

Here is a quote from the Backbone documentation:

If the model does not yet have an id, it is considered to be new.

It is clear from your code that you are assigning an id attribute. Your backend should be doing that. And since you are doing it on a client, backbone presumes it it not new, and uses PUT

mu is too short
  • 426,620
  • 70
  • 833
  • 800
tonino.j
  • 3,837
  • 28
  • 27
20

The above answers are correct in that if the model you are .save'ing has an id attribute backbone will do a PUT rather than a POST.

This behavior can be overridden simply by adding type: 'POST' to your save block:

var fooModel = new Backbone.Model({ id: 1});

fooModel.save(null, {
  type: 'POST'
});
Lane
  • 6,532
  • 5
  • 28
  • 27
  • 2
    Thanks for your post, it helped me in a similar case. I found out (reading the Backbone source) that you don't need to create the model, save it and then add to the collection, you just have to pass type:'POST' to the collection's create() method: fooCollection.create({id: 1}, {type:'POST'}); – Shu Aug 28 '14 at 15:59
  • For other solutions see: [What is the least ugly way to force Backbone.sync updates to use POST instead of PUT?](http://stackoverflow.com/q/8527694/1218980) – Emile Bergeron Dec 12 '16 at 02:10
3

You can specify the ID in defaults, just make sure it's set to null (isNew will be set to true).

In your case it must be

LineNo_: null
Alexander Volkov
  • 7,904
  • 1
  • 47
  • 44
seppestaes
  • 31
  • 2