简体   繁体   中英

Passing value from codebehind to js

I have this javascript code that does show objects on the map:

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

But I want it to be populated from the database/c#. How can I do that?

How can i pass that kind of array from the my page_load to this js script?

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

You can serialize a C# array using JsonConvert.SerializeObject . eg

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

In Javascript:

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

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

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

</script>

You can also declare the variable from C#:

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

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