[英]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). 我目前正在开发一个ASP.NET MVC解决方案,最近又推出了Knockout(MVVM JS库)和Wijmo(一组jQuery UI小部件)。
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()"
. 随着Knockout的引入,我还需要在客户端有模型,所以为此我将序列化C#ViewModel并使用
data-model="@Model.ToJson()"
将其附加到视图中。 This allows me to retrieve the model from JS and apply some client-side love to everything. 这允许我从JS检索模型并对一切应用一些客户端的爱。
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. 但是,knockout需要一切都是可观察的,所以我需要声明一个单独的客户端ViewModel并映射数据模型对象的所有内容。 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. 我希望有人有一个共享的工具或技术,这将允许我直接从服务器渲染淘汰ViewModel。 Possible solution could include:
可能的解决方案包括:
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 根据他们的教程,它只是一个简单的
.map
函数
If this is the ViewModel 如果这是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 此函数从服务器获取数据,它使用
.map
函数将服务器数据直接注入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 对于ko映射http://knockoutjs.com/documentation/plugins-mapping.html
For auto-bind here's an example 对于自动绑定,这是一个例子
https://groups.google.com/forum/#!msg/knockoutjs/IJTx37UXQVw/UTrWdEK1C-oJ https://groups.google.com/forum/#!msg/knockoutjs/IJTx37UXQVw/UTrWdEK1C-oJ
试试这个适用于visual studio的插件http://visualstudiogallery.msdn.microsoft.com/32c15a80-1c54-4e96-a83f-7cd57573a5d2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.