2

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?

2

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.