将字符串数组从c#传递到javascript

本文关键字:javascript 字符串 数组 | 更新日期: 2023-09-27 18:28:57

我正在c#中构建两个数组,并将它们传递给如下的js函数:

            //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);

由于某种未知的原因,这在这里引发了一个异常(在aspx页面中,生成的js的一部分):

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

上面写着:

Uncaught SyntaxError: Unexpected token ]

你能告诉我哪里错了吗?

将字符串数组从c#传递到javascript

使用@Skilwz建议(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);