[英]Passing array of strings from c# to javascript
I am building two arrays in c# and pass them to a js function like this: 我在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);
For some unknown reason this throws an exception here (in the aspx page, part of generated js): 由于某些未知的原因,这会在此处引发异常(在aspx页中,生成的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
): 使用@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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.