将模型数据传递给外部 javascript
有没有办法将模型数据传递到外部 JavaScript,而无需在视图上隐藏变量。我正在使用 Google 地图显示图钉,地图是通过 javascript 加载的,同时我有(大)纬度、经度信息列表,作为我的模型数据的一部分,该数据是在我的请求期间获取的。我不想在我的 html 中有一长串隐藏变量,也不想再对服务器进行一次 ajax 调用,以在我的 javascript 中获取所需的信息(纬度/经度)。有什么办法可以有效地做到这一点吗?
谢谢。
Is there a way to pass the Model data to external javascript without having hidden variables on my View. I am using Google map to display pushpins and the map is loaded via javascript and at the same time I have (big)list of latitude, longitude information as a part of my Model data which is fetched during my request. I do not want to have a long list of hidden variables in my html and also reduce one more ajax call to the server to fetch the required information(lat/lon) in my javascript. Is there any way to do this efficiently?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简短的回答是“不”。
如果您需要在视图旁边返回原始数据模型,唯一的选择是将数据嵌入视图中。这两个选项是:
在 HTML 元素中(IMO 有点尴尬):
在脚本中:
我更喜欢第二种方法,因为没有 HTML 转义。
我同意必须这样做有点烦人,但一个请求就是一个请求......它只是一个数据流。以这种方式引导数据相当常见,因此 MVC 的未来版本可能会有一种更简洁的方式来返回它(但它可能看起来就像我上面的示例之一)。
除此之外,正如您所提到的,您可以执行额外的请求来仅接收 JSON 响应中的模型。
编辑:
我有一个 HtmlHelper 来帮助解决这个问题...
用法:
结果:
The short answer is "no."
If you need to return a raw data model alongside your view, the only option is to embed the data in the view. The two options are:
In an HTML element (kind of awkward IMO):
In script:
I prefer the second method as there is no HTML escaping.
I agree it is kind of annoying to have to do this, but one request is one request... it is just one stream of data. Bootstrapping data in this way is fairly common, so maybe a future version of MVC will have a cleaner way to return it (but it would probably look just like one of my examples above).
Outside of that, as you mentioned, you can do an extra request to receive just the model in a JSON response.
EDIT:
I had a HtmlHelper up my sleeve to help with this...
Usage:
Result: