KnockoutJs Creating View Model With And Without MVC.Net

Content

  1. How to Create view model in knockoutJs manually.
  2. How to Create  view model in knockout automatically using mapping plugin.
  3. How to Create  view model in knockout using Server side model in .Net MVC and ko mapping plugin.

When has different ways of creating the View Model when used with and without MVC .Net .In this post we will explore the different way sof creating view Models in knouckoutJs

1 . Create view model in KnockoutJs manually –

koWithJs

Similarly if you have 30 40 properties in your model then you have to manually define those properties in your dataItem model and then fill them manually. This sounds very tedious.

Another alternative is to use the the knockout mapping plugin which will map the ajax data directly to your dataItem view model.Here is the sample code for the same.

2. Create  view model in knockout automatically using mapping plugin.

koWithmappingJs

Mapping plugin dependency – you will also have to refer the mapping js from ko apart from the knockout script file.

this saves a lot of time as you do not have to create custom properties and map them individually.

Knockout with MVC .Net
When we use knockout with MVC we can leverage the model that is bound to the view to create our view model’s structure.This means that you can pass data normally to your view from your controller action and knockout will use this server side model to create it’s client side view model structure.

This is how we do it –

3. Create  view model in knockout using mapping plugin in MVC.Net

koWithMVC

 //var viewModel = ko.mapping.fromJS(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));

This simple line of code does the magic it again uses the knockout mapping plugin and serializes the server side model as JSON object using the Newtonsoft serializer and then maps it directly to client side knockout model using the mapping plugin.
Now you can use this  viewModel and bind it directly to your view just as you bind a ko model . All the properties in this veiw model will be observable.