简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM