Tag Archives: KnockoutJS

Creating a KnockoutJS Model From an ASP.NET MVC Model

The Problem

In the previous article I showed how to load and populate an existing KnockoutJS view model which mirrored the properties of a C# model.  There is an obvious problem relating to maintainability here; when the C# model changes we need to manually update the KnockoutJS view model.  Fortunately there is a solution!

The Solution

To deal with this problem we can use the Knockout Mapping plugin which provides functionality to map JSON to KnockoutJS observables; you can either get it from the website or through NuGet.

If we simply want to map JSON to observables we can just use the mapping functionality of the plugin and use the return value directly as a view model.  The example below demonstrates this usage:

1 2 3 4 5 6 7 8 9 10 11 12
@using Quickstart.Web.Extensions
@model Quickstart.Web.Models.Person
@section scripts
{
<script type=“text/javascript”>
var viewModel = ko.mapping.fromJS(@Html.Raw(Model.ToJson()));
ko.applyBindings(viewModel);
</script>
}
<!– HTML for view knockout bindings etc –>

Note the use of the ToJson() extension method from the previous article

While this approach works to create a simple model, it is more likely that you will want to have a more complex view model which defines functions and calculated observables.  To accomplish this we simply need to create a typical KnockoutJS view model and use the mapping plugin within it:

1 2 3 4 5 6 7 8 9
var DynamicModelLoading = function(data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.displayFullName = function(model) {
var fullName = model.firstName() + ” “ + model.lastName();
alert(fullName);
};
};

Here we give the “fromJS()” function three parameters:

  • The data: the JSON to be used to generate the observable variables
  • The mapping configuration: used to customise the mapping process (beyond the scope of this series but the documentation may be useful)
  • The update target: the object to create observables in

In the example above the data is the C# model serialized as JSON and the update target is the “self” variable which references the view model object itself.  This view model also defines a simple function which constructs and displays the Persons full name which can be bound to in the view.  This view model can then be created and applied to the view:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
@using Quickstart.Web.Extensions
@model Quickstart.Web.Models.Person
@section scripts
{
<script type=“text/javascript” src=“/Scripts/ViewModels/DynamicModelLoading.js”></script>
<script type=“text/javascript”>
var viewModel = new DynamicModelLoading(@Html.Raw(Model.ToJson()));
ko.applyBindings(viewModel);
</script>
}
<!– HTML for view knockout bindings etc –>
<a href=“#” databind=“click:displayFullName”>Display full name</a>

Refrence:-

http://blog.json.codes/web-development/creating-a-knockoutjs-model-from-an-asp-net-mvc-model/

Advertisements