Skip to content

Using KO with ASP.NET MVC

paultyng edited this page Nov 15, 2011 · 1 revision

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

There 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 this method you can serialize an object (typically your MVC Model class) directly in your Javascript code using something similar to:

ko.mapping.fromJS(@Json.Encode(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: