问题
If I had a model like this in my MVC3 application:
public class Person
{
public Guid Id { get; set; }
public Name Name { get; set; }
public Address Address { get; set; }
public PhoneNumber PhoneNumber { get; set; }
}
public class Name
{
public string First { get; set; }
public string Last { get; set; }
}
public class Address
{
public string AddressLine { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
How would do I populate it with .fetch()
from backbone.js?
This is what I tried:
class Person extends Backbone.Model
$ ->
person = new Person()
person.fetch()
// person.get for things like Name.First, or Name, or First
// all return undefined
alert person.get( ... ) // ?
I have the appropriate JsonResult Action method and control, and have verified with Fiddler that the fetch()
call is properly returning the Json data. (Which I can post tomorrow morning from the office)
I'm really new at Backbone, what am I doing wrong?
回答1:
Couple things: 1) fetch is async. Try this:
person.fetch({
success: function() {
alert(person.get('Name')
}
});
2) This will show that the name property is an object (but not a backbone model):
{
Name: "Joe"
etc...
}
You may want to use Backbone.Relational or something similar if you want Name to be a backbone model. or you can override parse to flatten out your json.
来源:https://stackoverflow.com/questions/9594403/how-do-i-fetch-a-backbone-js-model-from-serialized-json-from-a-mvc3-model