Skip to content

Using KO with ASP.NET MVC

Jeremy Cook edited this page Apr 29, 2014 · 4 revisions

There are multiple patterns to use when implementing a page combining Knockout with ASP.NET MVC. Mostly it depends upon whether you will have your ViewModel refreshing from the server without reloading the page.

ViewModel Loaded in Ajax

To load your view model in Ajax you can use the built in JsonResult functionality in the actions that load your data with the ko.mapping plugin. The mapping plugin handles wiring up your JSON objects as observables for UI binding so you won't need to explicitly do so.

ViewModel Loaded in View

Multiple ways to load a static ViewModel in your view:

Explicit ViewModel javascript coding with value assignment

In your MVC view you can manually code the ViewModel class by hand and assign values (make sure to escape things properly to avoid injection issues).

var viewModel = {
    property1: @Model.SomeValue
};

Using Json.NET to JSON encode your server-side Model directly in your view

This method avoids "the nightmare that is JSON Dates" because it uses Json.NET instead of Microsoft's own Json.Encode. It comes standard in newer versions of ASP.NET MVC, but you can also get Json.NET from NuGet. Note the use of the JavaScript method JSON.parse and HttpUtility.JavaScriptStringEncode server-side to avoid injection issues by escaping output.

JSON.parse("@Html.Raw(HttpUtility.JavaScriptStringEncode(
    JsonConvert.SerializeObject(Model)
))");

Like Json.NET, this method can serialize an object (typically your MVC Model class) directly in your Javascript code, but you may discover that the non-standard JSON it outputs is more trouble than it is worth.

@Json.Encode(Model)

The mapping plugin gives you a straightforward way to map a plain JavaScript object into a view model with the appropriate observables. This is an alternative to manually writing your own JavaScript code that constructs a view model based on some data you’ve fetched from the server.

ko.mapping.fromJS(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)))

Serializing directly to an object decorated with observables

There are some third party libraries or custom code HTML helpers that can help you to automatically write out a javascript object with Knockout observables or tags with the data-bind attribute. Here are a few of them:

Handle complex scenarios with custom JS view models

Automated tools like those listed above are great—except when they're not. Don't forget about rolling your own JavaScript view model. Although not specific to MVC, here is a great example of just that: