简体   繁体   English

将JavaScript代码添加到动态查看

[英]Add JavaScript code to View dynamically

I have some code to display a google map. 我有一些代码来显示谷歌地图。 In my controller, I create the javascript: 在我的控制器中,创建javascript:

MapCode = string.Format("<script type='text/javascript'>init_map('my_map', {0}, {1}, 20)</script>", location.Location.Coordinate.Latitude, location.Location.Coordinate.Longitude)

But I can't just write that to my view: 但是我不能只是将其写到我的观点:

@Model.MapCode @ Model.MapCode

Because that just displays the actual javascript - doesn't execute it. 因为那只会显示实际的javascript-不会执行它。

Is there a way to do this? 有没有办法做到这一点?

使用HtmlHelper.Raw()输出原始HTML,而不对视图进行编码。

@Html.Raw(Model.MapCode)

You could pass location.Location as the model and then do this on your view: 您可以将location.Location作为模型传递,然后在视图上执行此操作:

<script type='text/javascript'>init_map('my_map', '@Model.Coordinate.Latitude', '@Model.Coordinate.Longitude', 20)</script>

In that manner you don't have to build your script from the controller, which is always not a good idea. 这样,您不必从控制器构建脚本,这始终不是一个好主意。

I don't see mixing server-side and client-side (JavaScript and C#) code as a good practice. 我不认为将服务器端和客户端(JavaScript和C#)代码混合是一种好习惯。

Alternative you can use jQuery.getScript() if you are using jQuery. 或者,如果您使用的是jQuery,则可以使用jQuery.getScript() That way you can create AJAX request to get data and do that in AJAX callback. 这样,您可以创建AJAX请求以获取数据并在AJAX回调中进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM