2

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.

1 Answer 1

5

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.