This is a little deep dive that came out of a previous post on my SignalR Series.
First, let's talk about a little background. The popularity of the Single Page Application (SPA) has seen its rise and fall, as companies like twitter moved from server side page rendering to loading the initial page with Ajax calls back to the server. Then after a few months, they moved back to initial server side rendering because of the perceived page load to the browser. After all, the aspect of user experience that matters on the web is perceived page load.
Now, let's fast forward. While we can deliver a faster initial page load using server side rendering, if we want to update the web page after it has loaded with data from an Ajax call, we get into a dilemma of having both server side templates and client side templates to maintain. This is the part that sucks from a code maintainability aspect. This means extra work when you add a new feature or fix a bug. Even worse, you may fix a bug in one and not realize it needed to be fixed in the other template technology.
There are two pieces of code needed to make this solution work.
Access the mapping plug in by calling
ko.mapping in the view and pass in the JSON representation of your server side view model. That brings us to the
.ToJson extension method. This is a small piece of code I wrote to simplify the Json serialization using Json.Net.
This little trick will simplify your code maintenance and also clean up your client side view models, by reducing the amount of object initialization you need to write. This really comes into play when you have a number of collections on your viewmodel.