Jquery – Backbone.js with ASP.NET MVC

asp.net-mvc-3backbone.jsjqueryjquery-templatesknockout.js

In the last few days I've been reading about Backbone.js and how it simplifies JS code interaction with View elements, basically within HTML. I've also read about the differences between KnockoutJS and Backbone.js. Now I'm thinking whether using one or the other inevitably leads to duplicating the code that we already have in our MVC app (mostly ViewModels and routes in global.asax) inside our Views. Essentially requiring us to code another set of Models in Backbone or Knockout. As I understand, with KnockoutJS this is even more prevalent, that's why I thought I will choose Backbone but now I think it is not that different – after a few examples I saw that same duplication is becoming evident.

Also how do we maintain such an application if for instance we already have a bunch of MVC Partial Views and now we are supposed to recreate them in Backbone using some templating engine like JQuery templates?

Best Answer

Have been reading about backbone and knockoutjs myself lately, and was also pondering about how to leverage the framework with asp.net mvc. One approach to avoid the duplication of models is to serialize (json) the server side viewmodel and use it as your backbone or knockout model. Positive side effect, your client side models already contain the data on page load and don't have to fetch the data via an ajax request when the page is first loaded. I'm aware that only serializing the serverside viewmodel isn't enough for backbone/knockout, but it could be a starting point. Perhaps the serialized model could be a property on the clientside model.

About jquery templates, I usually put a jquery template in a partial view. This way they are easily rendered in your view like this:

<script id="SomeTemplate" type="text/x-jquery-tmpl">
    @Html.Partial("Templates/SomeTemplate")
</script>

Obviously, porting an existing application to leverage jquery templates will take some time and effort.