简体   繁体   中英

Add JavaScript code to View dynamically

I have some code to display a google map. In my controller, I create the 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

Because that just displays the actual javascript - doesn't execute it.

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:

<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.

Alternative you can use jQuery.getScript() if you are using jQuery. That way you can create AJAX request to get data and do that in AJAX callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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