根据服务器的初始标记填充knockoutJS视图模型对象 [英] Populate knockoutJS view model object based on an initial markup from the server

查看:70
本文介绍了根据服务器的初始标记填充knockoutJS视图模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网络服务器返回一个带有结构化标记的页面。我需要使用knockoutJS将一个标记表示作为JSON对象 - 淘汰视图模型对象。

My web server returns a page with some structured markup. I need to use knockoutJS to have a markup representation at hand as a JSON object - knockout view model object.

该页面基本上(在初始加载后)a < div data-bind =foreach:ExistingNamings> 有几个封闭的div实际上包含应该进入视图模型对象的ExistingNamings数组的东西。

The page basically has (right after initial loading) a <div data-bind="foreach: ExistingNamings"> that has several enclosed divs that actually hold stuff that supposed to go into the ExistingNamings array on the view model object.

可以根据调用 ko.applyBindings ?

关于KNJS的教程显示相反的情况 - 我们在JS中有一个数据生成代码,并在applyBindings调用时被推送到html。

A tutorial on KNJS shows the opposite - we have a data generation code in JS, and that gets pushed into an html upon applyBindings call.

PS我的服务器端是ASP.NET MVC,我见过有人建议 http://knockoutmvc.com/ - 为js文件生成初始化代码的方法。这种方式是仿佛视图模型通过javascript初始化。这是处理初始数据的唯一方法,还是我确实可以解析标记?

P.S. My server side is ASP.NET MVC, and I've seen people suggesting http://knockoutmvc.com/ - an approach to generate initialization code for js file. This way it is "as if" view model is initialized via javascript. Is this the only way of dealing with initial data, or I indeed can parse markup?

推荐答案

您可以使用razor直接将C#模型序列化为JSON:

You can directly serialize your C# models into JSON using razor like this:

var serverModel = @Html.Raw(Json.Encode(Model));

或者,显然:

var serverProperty = @Html.Raw(Json.Encode(Model.Property));

这次失败的唯一时间是你有循环引用,如果你放弃你的实体就会发生这种情况如果您这样做,请为它们创建一个ViewModel,以消除圆形导航属性。

The only time this fails is when you have circular references, which can happen if you are dropping your Entity models directly in. If you are doing this, make a ViewModel for them, to eliminate the circular navigation properties.

更新:

要将其添加到您的viewModel中,请将其添加到Razor视图的底部:

To get this into your viewModel, add this to the bottom of your Razor View:

<script type="text/javascript">
    var serverModel = @Html.Raw(Json.Encode(Model));    
    //Define KO viewModel, either here, or by including via script tag in header    
    ko.applyBinding(new ViewModel(serverModel));
</script>

这篇关于根据服务器的初始标记填充knockoutJS视图模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆