在Razor中将模型分配给Javascript变量 [英] Assigning the Model to a Javascript variable in Razor

查看:99
本文介绍了在Razor中将模型分配给Javascript变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到包含某些对象的集合(列表)的对象的强类型视图.我知道Razor在生成页面时会在服务器端执行,而Javascript变量要等到页面显示后才能实例化...但是可以通过某种方式转换Model(将视图绑定到)或Razor中JSON的任何字段,而无需诉诸AJAX调用来随后获取该数据?

I have a strongly-typed view bound to an object which contains a Collection (list) of some objects. I know Razor gets executed on the server-side when it's generating the page, whereas Javascript variables don't get instantiated until after the page is displayed... but would it somehow be possible to convert the Model (that the view is bound to) or any of its fields to JSON in Razor without resorting to an AJAX call to fetch that data afterwards?

你知道,类似...

var myJavascriptVariable = @Model.MyCollection

其中@Model.MyCollection是一些对象的列表.

where @Model.MyCollection is a list of some objects.

谢谢

推荐答案

要获取json数据,可以使用以下结构:

To get json data you can use the following construction:

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

这篇关于在Razor中将模型分配给Javascript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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