将值从代码隐藏传递给js

时间:2018-10-25 17:54:21

标签: javascript c# asp.net arrays

我有这个JavaScript代码,它确实在地图上显示了对象:

 <script type="text/javascript">
            google.maps.event.addDomListener(window, 'load', init);

            function init() {
                var locations = [
                    [40.6128, -73.9976, "images/pin-apartment.png", "estate-details-right-sidebar.html", "images/infobox-offer1.jpg", "Fort Collins, Colorado 80523, USA", "$320 000"],[41.6926, -87.6021, "images/pin-house.png", "estate-details-right-sidebar.html", "images/infobox-offer5.jpg", "E. Elwood St. Phoenix, AZ 85034, USA", "$300 000"]
                ];

                offersMapInit("offers-map", locations);
            }

        </script>

但我希望从数据库/ c#中填充它。我怎样才能做到这一点?

如何将这种数组从我的page_load传递到此js脚本?

 protected void Page_Load(object sender, EventArgs e){}

1 个答案:

答案 0 :(得分:1)

您可以使用JsonConvert.SerializeObject序列化C#数组。例如

protected string StringArray { get; set;}
Page_Load(object sender, EventArgs e) {
   StringArray = JsonConvert.SerializeObject(new string[] {"foo", "bar"});
}

在Java语言中:

<script type="text/javascript">
    google.maps.event.addDomListener(window, 'load', init);

    function init() {
        var locations = <%= StringArray %>;

        offersMapInit("offers-map", locations);
    }

</script>

您还可以从C#声明变量:

var stringArray = JsonConvert.SerializeObject(new string[] {"foo", "bar"});
ClientScript.RegisterStartupScript(GetType(), "locations", $"var locations = {stringArray};", true);