2012-08-10 53 views
0

我有一個DataTable,我從數據庫中獲得,我想在後面的代碼中創建一個2d數組(一旦我得到DataTable ..),然後將其作爲2d傳遞數組轉換爲Javascript。傳遞2d數組從代碼背後到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沒有定義瀏覽器控制檯.. 我不知道我該怎麼做正確..

回答

1

可能該變量是在函數內部定義的,因此對於其他代碼部分是隱藏的。嘗試「window.videoQArray」 insted的的「變種」:

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)); 
+0

nope。同樣的錯誤.. – thormayer 2012-08-10 21:06:41

+1

謝謝!有效! – thormayer 2012-08-10 21:20:25

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];