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

How to inject model collection into backbone.js from asp.net mvc?

本文关键字:集合 模型 注入 backbone js mvc asp net      更新时间:2023-09-26

我在backbone.js中看到过一些例子,它说应该将初始模型集合引导到页面中,而不是出去获取它。这一点很有道理。出于某种原因,我不知道如何使用asp.net mvc应用程序来实现这一点。我在下面开始了一个快速的例子。

控制器动作:

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在我看来:

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

调用backbone.js应用程序中的collection.reset():

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

出于某种原因,这似乎不正确。

从模型中删除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>