This is a little deep dive that came out of a previous post on my SignalR Series.
Background
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.
The Problem
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.
A Solution
The solution using ASP.NET MVC and KnockoutJS is pretty simple. Rather than loading the viewmodel from an Ajax call, just write the viewmodel from the server side razor template as a JSON object into the JavaScript of the page. Then use the KnockoutJS Mapping plug in to map from the JSON object to the observable objects required by KnockoutJS. To install the mapping plug in, use the nuget package.
There are two pieces of code needed to make this solution work.
<script src="https://gist.github.com/4166568.js?file=gistfile1.html"></script>
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.
<script src="https://gist.github.com/4166568.js?file=ToJsonExtension.cs"></script>
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.