Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate client-side view models for knockout in an ASP.NET MVC project?

I am currently working on an ASP.NET MVC solution and have recently introduced both Knockout (an MVVM JS library) and Wijmo (a set of jQuery UI widgets).

With the introduction of Knockout I also need to have models on the client side, so for this purpose I am serializing the C# ViewModel and attaching it to the view using data-model="@Model.ToJson()". This allows me to retrieve the model from JS and apply some client-side love to everything.

However, knockout needs everything to be observables, so I need to declare a separate client-side ViewModel and map everything from the data-model object. This feels very much like duplicate effort and I'd like to avoid it somehow.

I'm hoping someone has a tool or technique to share that will allow me to render the knockout ViewModel directly from the server. Possible solution could include:

  • Custom JSON serialization to render the observable view model directly to the output in the data-model attribute.
  • Automatic client-side transformation (I've heard of ko-autobind, but am not sure if it would be a recommended path to take or how stable/complete it is)
  • Something I haven't thought of

I'd like the solution to be generic and automatic, as my current approach of typing the observable client-side view models by hand is just too unproductive to be viable.

How are you solving this problem?

like image 398
Morten Mertner Avatar asked Jun 02 '12 22:06

Morten Mertner


1 Answers

According to their tutorials it's just a simple .map function

If this is the ViewModel

function Task(data) {
    this.title = ko.observable(data.title);
    this.isDone = ko.observable(data.isDone);
}

And this function get's the data from the server, it uses the .map function to inject the server data right into the VM

// Data
var self = this;
self.tasks = ko.observableArray([]);

// Load initial state from server, convert it to Task instances, then populate self.tasks
$.getJSON("/tasks", function(allData) {
    var mappedTasks = $.map(allData, function(item) {
        return new Task(item)
    });
    self.tasks(mappedTasks);
});

For ko mapping http://knockoutjs.com/documentation/plugins-mapping.html

For auto-bind here's an example

https://groups.google.com/forum/#!msg/knockoutjs/IJTx37UXQVw/UTrWdEK1C-oJ

like image 186
CD Smith Avatar answered Oct 12 '22 13:10

CD Smith