简体   繁体   中英

Passing array of strings from c# to javascript

I am building two arrays in c# and pass them to a js function like this:

            //call js to show the map with the markers
        string[] lats = new string[10];
        string[] longs = new string[10];

        for (int i = 0; i < 10; i++)
        {
            lats[i] = dv[i]["Latitude"].ToString();
        }

        for (int i = 0; i < 10; i++)
        {
            longs[i] = dv[i]["Longitude"].ToString();
        }

        StringBuilder sbLats = new StringBuilder();
        string[] latsArray = lats.ToArray<string>();

        //Build the JS array.
        sbLats.Append("[");
        for (int i = 0; i < latsArray.Length; i++)
        {
            sbLats.AppendFormat("'{0}', ", latsArray[i]);

        }
        sbLats.Append("]");

        StringBuilder sbLongs = new StringBuilder();
        string[] longsArray = longs.ToArray<string>();

        //Build the JS array.
        sbLongs.Append("[");
        for (int i = 0; i < longs.Length; i++)
        {
            sbLongs.AppendFormat("'{0}', ", longsArray[i]);

        }
        sbLongs.Append("]");


        ScriptManager.RegisterStartupScript(this, this.GetType(), "mapMarket", "buildMapWithMarkers('map_market', " + latsArray + ", " + longsArray + ", " + "false" + ");", true);

For some unknown reason this throws an exception here (in the aspx page, part of generated js):

buildMapWithMarkers('map_market', System.String[], System.String[], false)

which says:

Uncaught SyntaxError: Unexpected token ]

Can you please tell me where I am wrong?

Solved it using @Skilwz suggestion ( JavaScriptSerializer ):

 //call js to show the map with the markers
        string[] lats = new string[10];
        string[] longs = new string[10];

        for (int i = 0; i < 10; i++)
        {
            lats[i] = dv[i]["Latitude"].ToString();
        }

        for (int i = 0; i < 10; i++)
        {
            longs[i] = dv[i]["Longitude"].ToString();
        }


        string serializedLat = (new JavaScriptSerializer()).Serialize(lats);
        string serializedLong = (new JavaScriptSerializer()).Serialize(longs);

        ScriptManager.RegisterStartupScript(this, this.GetType(), "mapMarket", "buildMapWithMarkers('map_market', " + serializedLat + ", " + serializedLong + ", " + "false" + ");", 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