如何在使用Razor的javascript中使用服务器端变量

时间:2011-07-12 20:25:03

标签: javascript razor

我在视图中有一段代码

@if (Model.Count() > 0)
{
    var locations = new List<string>();
    var count = 1;
    foreach (var shop in Model)
    {
        locations.Add(string.Format(
                    @"{{
                           title: ""Shop Name: {0}"", 
                           position: new google.maps.LatLng({1}, {2}),
                           icon: ""{3}""
                       }}",
                       shop.ShopName,
                       shop.Location.Latitude,
                       shop.Location.Longitude,
                       count
                    )
                  );

        count++;
    }

    var locationsJson = "[" + string.Join(",", locations.ToArray()) + "]";
}

如何将locationsJson指定为javascript变量

<script type="text/javascript">
    var jsLocations = @locationsJson;
</script>

3 个答案:

答案 0 :(得分:2)

在服务器端执行嵌入式服务器代码,然后您可以将其作为模型的属性并执行以下操作:

<script type="text/javascript">

var jsLocations = @Model.locationsJson;

</script>

答案 1 :(得分:1)

  

我在视图中有一段代码

你绝对不应该在你的视图中有这样的代码。试试这个(更短,更好,更安全):

<script type="text/javascript">
    var jsLocations = @Html.Raw(Json.Encode(Model));
    $.each(jsLocations, function(index, item) {
        // TODO: do something with the item, for example
        // alert(item.ShopName); or alert(Location.Latitude);
    });
</script>

答案 2 :(得分:0)

您的代码可以正常使用。

但是,您需要转义JSON中的值,否则您将有一个XSS漏洞 您应该使用真正的JSON序列化程序。