1

I am using backbone.js in my mvc application and I have a scenario where I have to pass an array to my Post method in Rest API. I am trying to send an array of models and then calling this.collection.create(model). I am trying to call the Post method as

var myArrayofModels = JSON.stringify(e.models);
this.collection.create(myArrayofModels );

Here e.models is an array of models which I convert to json and call Post method and I want to receive array of models on Post method like this

public HttpResponseMessage Post(InsuranceAddressViewModel[] model)
{
    return null;
}       

But I am getting null array in Post method. Is my method of converting array of models to json is fine or will have to do something else. I have tried couple of solutions but couldn't get idea.

Bart
  • 19,692
  • 7
  • 68
  • 77
touseefkhan4pk
  • 473
  • 4
  • 26

1 Answers1

1

The answer can be found on Stack Overflow. Basically you store a collection inside a model and then override the toJSON method inside the model. A quick example can be seen below.

var ModelArray = Backbone.Model.extend({
  toJSON: function() {
     return this.collection.toJSON();
  }
});

var modelCollection = new ModelArray({ collection: collectionOfModels })

modelCollection.save();

Your controller should then pickup the properly formatted array of models you are trying to save.

Community
  • 1
  • 1
TYRONEMICHAEL
  • 4,174
  • 4
  • 30
  • 47