I'm fetching a backbone collection using .NET MVC and am having trouble populating the collection properly. The data I need is returned but is inserted incorrectly in the collection.
What follows is all the details related to fetching the collection.
My model
_.namespace('My.Model');
My.Model.UserAssistance = Backbone.Model.extend({
defaults: {
Id : '',
Title: '',
Content: '',
Width: 175,
Popover: true,
ArrowPosition: "top-left",
ArrowDimensions: {
width: 0,
height: 0
}
}
});
My collection
_.namespace('My.Collection');
My.Collection.UserAssistance = Backbone.Collection.extend({
url: function () {
return '/user-assistance'
},
model: My.Model.UserAssistance
});
Fetching the collection
this.collection = new My.Collection.UserAssistance();
var $elements = $('[data-help-id]'),
values = $elements.map(function () {
return $(this).data('help-id');
}).get();
this.collection.fetch({
data: {
HelpIds : values
},
// required for correct serialization of the array
traditional: true
});
Controller method
[Authorize]
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult Default(List<string> HelpIds)
{
List<UserAssistanceViewModel> models = new List<UserAssistanceViewModel>();
foreach (string helpId in HelpIds)
{
UserAssistanceViewModel model = new UserAssistanceViewModel();
model.Content = (Resources.UserAssistance.Content.GetResourceById(helpId));
model.Title = (Resources.UserAssistance.Titles.GetResourceById(helpId));
model.Id = helpId;
models.Add(model);
}
return Json(new
{
models : models
}, JsonRequestBehavior.AllowGet);
}
When the collection is returned the collection is updated as follows:
userAssistance.collection.toJSON()
[
Object
ArrowDimensions: Object
ArrowPosition: "top-left"
Content: ""
Id: ""
Popover: true
Title: ""
Width: 175
models: Array[6]
0: Object
1: Object
2: Object
3: Object
4: Object
5: Object
length: 6
__proto__: Array[0]
__proto__: Object
I'm clearly doing something wrong but I don't know how else to format the data to be returned. You can see that it's actually adding a sub level in the form of an array of object called "models".