-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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.
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
};
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)
))");
Using Json.Encode
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)
Using the ko.mapping
plugin
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)))
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:
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: