2012-02-25 80 views
2

好吧,我知道这是一个远射。backbone.js从asp.net填充大型嵌套模型mvc viewmodel

我在后端使用asp.net mvc。我将有一个操作返回一个json viewmodel,它将包含几个简单的属性以及对象和对象集合。例如

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;} 
} 

一个SelectListType只是一个名字值对“文本”和“价值”,并在其“选择”属性

的想法是,有一个表单,您可以创建一个人通过填写名字,姓氏和从下拉列表中选择一个用户类型。

我想做什么就能做的是有一组Backbone.js的车型如

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

,并能够通过传递JSON来填充MyViewModel来自这将是服务器返回像这样的东西

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

这不是我知道的传统方式。我想我应该为每个对象或某个对象调用一次,但我真的只想要一次调用服务器来获取所需的所有数据,因为它已经在服务器上正确收集和排列。

我可以编写各种循环来填充所有不同的集合等,一旦数据到达,但没有一些更有效的方式来做到这一点?

回答

1

车CK出backbone-relational

如果您设置了关系,你可以做类似如下示例的东西:

paul = new Person({ 
id: 'person-1', 
name: 'Paul', 
user: { id: 'user-1', login: 'dude', email: '[email protected]' } 
}); 

// A User object is automatically created from the JSON; so 'login' returns 'dude'. 
paul.get('user').get('login'); 

否则,你也许可以完成你想要的东西通过重载解析()和的toJSON ()在你的MyViewModel中。

+0

我已经看过骨干关系,但不知道它会做我所需要的东西,它看起来像一大堆我不需要的东西,但如果它确实有效,那么这将是值得的,会很棒的。谢谢 – Raif 2012-02-26 01:16:54

1

在服务器上:

public ActionResult Index() 
{ 
    ViewModel model = ... 
    return View(model); 
} 

,并在客户端上:

@model ViewModel 
<script type="text/javascript"> 
    var model = @Html.Raw(Json.Encode(Model)); 
    // TODO: the model variable here will represent the 
    // structure you are looking for so you can hook it 
    // up with backbone 
</script> 

,如果你正在使用ASP.NET MVC 2和的WebForms查看发动机,其中,Json.Encode助手不可用你可直接使用JavaScriptSerializer类:

<script type="text/javascript"> 
    var model = <%= new JavaScriptSerializer.Serialize(Model) %>; 
    // TODO: the model variable here will represent the 
    // structure you are looking for so you can hook it 
    // up with backbone 
</script> 
+0

是的这会给我一个JavaScript变量的JSON,但它不会填充我的骨干模型。 – Raif 2012-02-25 23:51:29

+0

@Raif,对不起,我不明白你的问题。它似乎与骨干相关,并与ASP.NET MVC无关。 – 2012-02-26 08:27:51

+0

这是正确的,除了服务器运行mvc并生成一个丰富的viewmodel它返回到客户端。主干通常提倡(如果我理解正确的话)将每个对象调用到服务器以单独填充或每种类型的模型,而不是一次发送大量数据。 – Raif 2012-02-26 14:48:37