Loading KnockoutJS View Models from ASP.Net MVC, for faster page loads

This is a little deep dive that came out of a previous post on my SignalR Series.



First lets 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 renering 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, lets 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 on 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 then 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 plugin to map from the json object to the observable objects required by KnockoutJS. To install the mapping plugin, use the nuget package.

There are two pieces of code needed to make this solution work.

Access the mapping plugin 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.

Follow me on RSS and Twitter

Portable Areas three years later – Part 5