We are about to break our controllers up: actions that return semi-static HTML pages, actions that return JSON ViewModels and finally actions that post changes. We plan on using JSON.NET to do the JSON serialization since it supports a spiffy LINQ-like syntax for creating complex JSON objects. We will use jQuery+AJAX to call the JSON actions and use the results to replace elements in the HTML.
Before, we were passing ViewModels to the View() method and using it with Razor to fill in the screens. So the real big difference is that our view models will be JSON objects and JavaScript will be building the pages. The problem with the Razor syntax was that it was acting as a crutch. A lot of times we were mangling Razor and JavaScript (Frankenstein). Plus, a few pages take long enough to load that some sort of up-front feedback is needed anyway (loading...).
To the question: I have been looking at my code and have noticed that many ViewModels share common properties. Furthermore, the same logic is appearing across multiple controllers. I have been wondering what patterns/tools are out there for putting this logic into one place. Also, should I be trying to create a "master" ViewModel with child ViewModels (with other child ViewModels and so on)? The idea being that some elements are shared across all pages (such as header and footer content) and so it would seem to make sense to have a common ViewModel structure for each page. That way I can reuse the some JavaScript for finding data and setting it in the HTML. I figure if a page doesn't use a child ViewModel, I would just pass null, so it wouldn't take up too much space.
I want to make sure that I get things right before I start going down this new path. I have seen applications that use the hierarchy of ViewModels before and have seen problems because of it. I also want to keep the number of AJAX calls down, so I want to return as much data as possible in as few calls as possible. They are kind of contradicting requirements. I was hoping someone had experience with building lots of ViewModels and and with converting these to JSON objects for consumption on the client side. I was also curious if anyone found any tools for JavaScript for building pages from ViewModels. We are looking at backbone.js right now, but it seems oriented towards forms rather than generic content generation.
The idea being that some elements are shared across all pages (such as header and footer content) and so it would seem to make sense to have a common ViewModel structure for each page.
You should consider using partial views and master pages to accomplish this if you aren't already. Both are very useful and powerful tools.
I was also curious if anyone found any tools for JavaScript for building pages from ViewModels.
An extremely powerful JavaScript library that uses the MVVM pattern is Knockout.js. The twenty minute introduction video on the home page explains it very clearly.