Frankie
Frankie

Reputation: 2265

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

I've seen examples in backbone.js where it says the initial model collection should be bootstrapped into the page instead of going out to fetch it. That point makes sense. For some reason, I cannot figure out how to do it using an asp.net mvc application. I started a quick example below.

Controller Action:

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

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

    return View(model);
}

View Model: Here I am creating the json needed to inject my customer list into the app.

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

Decoding the json in my view:

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

Calling collection.reset() in backbone.js app:

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

For some reason this does not seem to work correctly.

Upvotes: 2

Views: 1032

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Remove the CustomJson property from your model. You don't need it.

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

is enough.

And then in your view:

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

would generate something along the lines of:

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

Upvotes: 5

Related Questions