我在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 ]
你能告诉我我哪里错了吗?
答案 0 :(得分:4)
使用@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);