简体   繁体   English

使用Javascript渲染时取消对服务器端字符串的编码

[英]Unencode server side string when rendering in Javascript

I am returning a model from my controller that displays a grid. 我要从显示网格的控制器返回模型。 Works fine. 工作正常。 I also need to use that same data to produce points on a google map. 我还需要使用相同的数据在Google地图上产生点。 I have the following code set up in my prototype that I needed to replace: 我在原型中设置了以下代码,需要替换它们:

            var locationsAll = [
                ["Pretty", 40.1508, -83.21],
                ["Little", 40.1308, -83.11],
                ["Smug", 40.001, -83.01],
                ["Troublemaker", 40.109, -83.291],
                ["Smallest", 40.08, -83.20]
                ];

            PlotpointsonMap(locationsAll);

So far so good. 到现在为止还挺好。 That works so I am converting this to javascript like so: 那行得通,所以我将其转换为javascript,如下所示:

                @{
                    var locations = "[";
                   foreach (var gmap in Model.MapPoints )
                   {
                       locations += "['" + gmap.EventStringData + "'," + gmap.Latitude + "," + gmap.Longitude + "],";
                   }

                    locations = locations.TrimEnd(',') + "]";

                }

            var myLocations = @locations;
            PlotpointsonMap(myLocations);

However, this half works. 但是,这一半有效。 I am getting the following code in my javascript block when I view the source generated: 查看生成的源代码时,我的javascript块中得到以下代码:

var myLocations = [["update",40.080398,-83.139141] 

I need it to render like so: 我需要它来这样渲染:

var myLocations = [["update",40.080398,-83.139141]

Any ideas on how to accomplish this are greatly appreciated. 任何有关如何完成此操作的想法都将受到赞赏。 I tried: 我试过了:

var myLocations = @Server.HtmlDecode(locations);

and it gave me the same result :( 它给了我相同的结果:(

Wooow, no! 哇,不! No manual JSON manipulation please. 请不要手动进行JSON操作 No commas, no quotes, no trims, no brackets please. 请没有逗号,没有引号,没有修剪,没有括号。 That hearts. 那颗心。

Simply use a JSON parser: 只需使用JSON解析器:

<script type="text/javascript">
    var locationsAll = @Html.Raw(Json.Encode(
        Model.MapPoints.Select(x => new object[] 
        { 
            x.EventStringData, x.Latitude, x.Longitude 
        })
    ));
    PlotpointsonMap(locationsAll);
</script>

The JSON parser guarantees you now that no matter what data you have in this MapPoints it will always be properly encoded. JSON解析器现在向您保证,无论此MapPoints包含什么数据,都将始终对其进行正确编码。

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

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