How to Get ASP .NET MVC 4 and Knockout.js to Play Nice Together

I recently worked on an ASP .NET MVC 4 project that I wanted to enable Knockout.js on. I wanted to use C# ViewModels as much as possible and move to Knockout ViewModels as late as possible. Doing this manually would be painstakingly tedious and would result in duplicate ViewModels between C# and JS. There had to be a better way.

Luckily, there’s a NuGet package for that. Knockout.Mapping provides a mechanism to convert your server objects to a JSON formatted JS ViewModel.

Here are the steps required to convert your C# ViewModels to Knockout ViewModels in your MVC application:

  • Install the Knockout.Mapping NuGet Package - PM> Install-Package Knockout.Mapping -Version 2.2.2
  • Create your C# ViewModel and pass it to your View from your Controller (standard practice) - @model MyApp.Web.Models.MyViewModel
  • Serialize your C# ViewModel to JSON (see below)
  • Use Knockout.Mapping to automatically set up your Knockout observables (see below)
  • Apply bindings as normal
  • Profit!

Index.cshtml

@{
    var jsonData = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
}

<script type="text/javascript">
  $(function () {
      var vm = ko.mapping.fromJSON('@Html.Raw(jsonData)');
      ko.applyBindings(vm);
  });
</script>

If you view the source behind your running MVC application, you will be able to see the JSON View Model at the top and are now free to use knockout’s data-bind attributes on your form elements.

Creative Commons License

What do you think?