我有一个从数据库中获取的DataTable,我想在后面的代码中创建一个二维数组(一旦我得到DataTable ..),然后将它作为二维数组传递给Javascript。
这是我尝试编码的内容:
int[,] videoQarray = new int[dt_questionVideo.Rows.Count,dt_questionVideo.Columns.Count ];
string[,] videoQarrayTitle = new string[dt_questionVideo.Rows.Count, dt_questionVideo.Columns.Count ];
for (var i = 0; i < dt_questionVideo.Rows.Count ; i++)
{
for (int j = 0; j < dt_questionVideo.Columns.Count; j++)
{
videoQarray[i,j] = Convert.ToInt32(dt_questionVideo.Rows[i][0]);
videoQarrayTitle[i,j] = dt_questionVideo.Rows[i][1].ToString();
}
}
string createArrayScript = string.Format("var videQarray = [{0}];", string.Join(",", videoQarray));
createArrayScript += string.Format("var videQarrayList = [{0}];", string.Join(",", videoQarrayTitle));
Page.ClientScript.RegisterStartupScript(this.GetType(), "registerVideoQArray", createArrayScript, true);
好吧,在浏览器控制台中它说没有定义videoQarray .. 我想知道如何才能正确地做到这一点..
答案 0 :(得分:1)
可能变量是在函数内部定义的,因此对于代码的其他部分是隐藏的。尝试“var”的“window.videoQArray”:
string createArrayScript = string.Format("window.videQarray = [{0}];", string.Join(",", videoQarray));
createArrayScript += string.Format("window.videQarrayList = [{0}];", string.Join(",", videoQarrayTitle));
编辑:这是一个二维数组(好吧,你在问题中写得非常清楚,但我没看到)。使用JavaScriptSerializer
:
var serializer = new JavaScriptSerializer();
string createArrayScript = string.Format("window.videQarray = {0};", serializer.Serialize(videoQarray));
createArrayScript += string.Format("window.videQarrayList = {0};", serializer.Serialize(videoQarrayTitle));
答案 1 :(得分:0)
使用以下功能:
public static string ArrayToString2D(string[,] arr)
{
StringBuilder str = new StringBuilder();
str.Append("[['");
for (int k = 0; k < arr.GetLength(0); k++)
{
for (int l = 0; l < arr.GetLength(1); l++)
{
if (arr[k, l] == null)
str.Append("','");
else
str.Append(arr[k, l].ToString() + "','");
}
str.Remove(str.Length - 2, 2);
str.Append("],['");
}
str.Remove(str.Length - 4, 4);
str.Append("]]");
return str.ToString();
}
后面的代码中的具有以下属性:
private string[,] upperLabels ;
public string UpperLabel
{
get
{ return Utils.ArrayToString2D(upperLabels); }
}
在javascript中使用以下内容:
var upperSplitted = <%=UpperLabel%> ;
var value = upperSplitted[0][0];