Wednesday, December 26, 2012

How to use MVC templates and knockout

Recently I am wirting a MVC4 application with some CRUD operation.
MVC provide the templates view to make model view easier. Knockout is a good javascript library to provide the view model binding. Then how to use best of the two together?

Here is a link which shows a good example to use both.

Basically, the template view only needs to add the attribute data-bind with the model property name.
and the property name can get from ViewData.ModelMetaData.PropertyName.

The link above only shows how to add the data-binding to the template. There are still a few things to be done to use knockout.

Knockout needs a ViewModel javascript to track the items and the code sample only returns a C# Model object.

Here is the data transform maps needed.
C# <Object > ---> JSON (javascript object) ---> KnockOut ViewModel

1. To translate model to json, use the following code,
@Html.Raw(
Json.Encode(ViewData.Model));

However, Json class is from a System.Web.Helpers assembly, which not included by MVC4.
The assembly needs to be added to the project from GAC.

2. knockout mapping is a js library to convert javascript object to viewModel,
which can be downloaded from here..

ViewModel = ko.mapping.fromJS( jsonObj );

No comments: