2012-02-12 3 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アプリでcollection.reset()を呼び出す

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

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([{"Id":1,"Name":"Foo"}, {"Id":2,"Name":"Bar"}]); 
    ... 
</script> 
+0

パーフェクト:

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

はの線に沿って何かを生成します。本当にありがとう!!! – Frankie

関連する問題