-
Notifications
You must be signed in to change notification settings - Fork 0
Using KO with ASP.NET MVC
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.
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.
There multiple ways to load a static ViewModel in your view:
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
};
Json.Encode
with the ko.mapping
plugin
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))
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: