2012-02-12 50 views
2

我在backbone.js中看到了一些示例,它说初始模型集合应该引导到页面中,而不是去取出它。这一点是有道理的。出于某种原因,我无法弄清楚如何使用asp.net mvc应用程序来做到这一点。我在下面开始了一个快速示例。如何将模型集合从asp.net mvc注入到backbone.js中?

控制器动作:

public ActionResult Index() 
{ 
    CustomerRespository repository = new CustomerRespository(); 

    ViewModel model = new ViewModel(); 
    model.Customers = repository.GetAll();   

    return View(model); 
} 

视图模型:在这里,我要创造我的注入客户名单到应用程序所需要的JSON。

public List<Customer> Customers { get; set; } 
public string CustomerJson 
{ 
    get 
    { 
     JavaScriptSerializer serializer = new JavaScriptSerializer();     
     return serializer.Serialize(this.Customers);   
    } 
} 

解码在我看来,JSON:)在Backbone.js的应用

@{ string s = HttpUtility.HtmlDecode(Model.CustomerJson); } 

调用collection.reset(:

this.customers = new CustomerCollection(); 
this.customers.reset("@s"); 

出于某种原因,这似乎并不能正常工作。

回答

5

从您的模型中删除CustomJson属性。你不需要它。

public List<Customer> Customers { get; set; } 

就够了。

然后在您的视图:

<script type="text/javascript"> 
    this.customers = new CustomerCollection(); 
    this.customers.reset(@Html.Raw(Json.Encode(Model.Customers))); 
    ... 
</script> 

会产生沿着线的东西:

<script type="text/javascript"> 
    this.customers = new CustomerCollection(); 
    this.customers.reset([{"Id":1,"Name":"Foo"}, {"Id":2,"Name":"Bar"}]); 
    ... 
</script> 
+0

完美。非常感谢!!! – Frankie 2012-02-12 17:39:35

相关问题