我能在淘汰赛客户端视图模型在ASP.NET MVC项目? [英] How can I generate client-side view models for knockout in an ASP.NET MVC project?
问题描述
我目前工作的一个ASP.NET MVC解决方案,最近推出了两个淘汰赛(一个MVVM JS库),并Wijmo(一组的jQuery UI部件的)。
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).
由于采用淘汰赛的我还需要对客户端的机型,所以为此我序列化的C#视图模型,并使用数据模型=@模式将其连接到视图。的toJSON()
。这使我检索JS模型并应用一些客户端爱的一切。
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:
- 自定义JSON序列来直接呈现观察到的视图模型中的数据模型属性的输出。
- 自动客户端转换(我听说过KO-autobind的,但我不知道这是否会采取或如何稳定推荐路径/完成它)
- 的东西我都没有想到
我想该解决方案是通用和自动化,以我目前的手动输入可观察的客户端视图模型的方法太非生产性是可行的。
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?
推荐答案
根据他们的教程,它只是一个简单的 .MAP
函数
According to their tutorials it's just a simple .map
function
如果这是在视图模型
function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone);
}
和这个函数来获取的来自服务器的数据,它使用 .MAP
函数到服务器的数据权注入到VM
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);
});
有关こ映射
<一href=\"http://knockoutjs.com/documentation/plugins-mapping.html\">http://knockoutjs.com/documentation/plugins-mapping.html
有关自动绑定下面是一个例子
For auto-bind here's an example
<一个href=\"https://groups.google.com/forum/#!msg/knockoutjs/IJTx37UXQVw/UTrWdEK1C-oJ\">https://groups.google.com/forum/#!msg/knockoutjs/IJTx37UXQVw/UTrWdEK1C-oJ
这篇关于我能在淘汰赛客户端视图模型在ASP.NET MVC项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!