如何从asp.net mvc中将模型集合注入backbone.js?

Fra*_*kie 2 javascript c# asp.net asp.net-mvc

我在backbone.js中看过一些例子,它说初始模型集应该被引​​导到页面中而不是去取它.这一点是有道理的.出于某种原因,我无法弄清楚如何使用asp.net mvc应用程序.我在下面开了一个简单的例子.

控制器动作:

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

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

    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

View Model:这里我创建了将我的客户列表注入应用程序所需的json.

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

在我的视图中解码json:

@{ string s = HttpUtility.HtmlDecode(Model.CustomerJson); }
Run Code Online (Sandbox Code Playgroud)

在backbone.js app中调用collection.reset():

this.customers = new CustomerCollection();
this.customers.reset("@s");
Run Code Online (Sandbox Code Playgroud)

出于某种原因,这似乎无法正常工作.

Dar*_*rov 5

从模型中删除CustomJson属性.你不需要它.

public List<Customer> Customers { get; set; }
Run Code Online (Sandbox Code Playgroud)

足够.

然后在你看来:

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

会产生以下几点:

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