Search code examples
asp.net-mvcjsoncollectionsbackbone.jsmodels

backbone.js populate large nested model from asp.net mvc viewmodel


Ok I know this is a long shot.

I am using asp.net mvc on the backend. I will have an action that will return a json viewmodel that will have several simple properties as well as objects and collections of objects on it. For instance

public class ViewModel
{
    public string Name {get;set;}
    public Person Person {get;set;}
    public IEnumerable<SleectListItem> UserTypes {get;set;}
}
public class Person
{
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public int UserType {get;set;}
}

a SelectListType is just a name value pair with "Text" and "Value" and "Selected" properties on it

The idea is that there is a form where you can create a person by filling out there first name, last name and selecting a usertype from a dropdown list.

What I would like to be able to do is have a set of backbone.js models such as

app.MyViewModel=Backbone.Model.extend();
app.Person=Backbone.Model.extend();
app.SelectListItem=Backbone.Model.Extend();
app.UserTypes=Backbone.Collection.Extend({
  model:app.SelectListType
})

and be able to populate the MyViewModel by passing in the Json returned from the server which would be something like this

{Name:'SomeName',
 Person:{
     FirstName:'Frank',
     lastName:'Jones'
 },
 UserTypes:[{Text:'Admin',
       Value:1,
       selected:false},
      {text:'peon',
      Value:2,
      selected:false}

This is not the traditional way I know. I guess I'm supposed to have one call for each object or something but I really want to only have one call to the server to get all the data I need as it's already being collected and arranged properly on the server.

I could write all kinds of loops to populate all the different collections and so on once the data arrived but is there not some more efficient manner of doing this?


Solution

  • Check out backbone-relational:

    If you set up the relations, you can do something similar to the example on that page:

    paul = new Person({
    id: 'person-1',
    name: 'Paul',
    user: { id: 'user-1', login: 'dude', email: 'me@gmail.com' }
    });
    
    // A User object is automatically created from the JSON; so 'login' returns 'dude'.
    paul.get('user').get('login');
    

    Otherwise, you could probably accomplish what you want by overriding parse() and toJSON() in your MyViewModel.