2016-09-20 71 views
0

我從複選框列表中動態創建了複選框,並將此列表保存到會話中,並希望在複選框的onChange事件中從會話中獲取此複選框列表。 這是代碼。如何從JavaScript ASP.NET會話中獲取對象列表?

public static List <CheckBox> chklist = new List <CheckBox>(); 
    void arrinit() { 
     for (int i = 0; i < 31; i++) { 
      //initializing list of checkboxes 
      chklist.Add(new CheckBox()); 
     } 
    } 
    void show() { 
     for (int i = 0; i < 30; i++) { 
      TableCell cell4 = new TableCell(); 
      tRow.Cells.Add(cell4); 
      ((IParserAccessor) cell4).AddParsedSubObject(chklist[i]); 
      chklist[i].ID = "cbx_" + i.ToString(); 
      string a = "processChechBox('" + "ctl00_ContentPlaceHolder1_" + chklist[i].ID + "'); return false;"; 
      chklist[i].Attributes.Add("onChange", a); 
      chklist[i].Attributes.Add("runat", "server"); 
     } 
     Session["chk"] = chklist; 
    } 

    function processChechBox(id) { 
     //here is the javascript function for checkbox onChange event 
     debugger; 
     var containerRef = document.getElementById(id); 
     var data = document.getElementById(id); 
     data.value = '1'; 
     data.checked = true; 
     var a = '<%= Session["chk"]%>'; 
    } 

var a = '<%= Session["chk"]%>'; 此行返回System.Collections.Generic.List1[System.CheckBox]代替列表 processChechBox(id)這個函數被調用上的每個複選框選中。

回答

0

此行

<%= Session["chk"]%> 

會寫出來的

Session["chk"].ToString() 

相當於這顯然不是你想要的這裏。用這裏使用的'var a'完成什麼工作?

我的猜測是你真的想這樣的事情

<% var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); %> 
var jsVariable = <%= serializer.Serialize(((List<CheckBox>)Session["chk"]).ToArray()) %>; 

感謝:Pass C# ASP.NET array to Javascript array

+0

我複製並粘貼您的代碼和它給我的異常:「異常已通過調用的目標引發異常」 {} 和內部異常是: {「這操作需要IIS集成管道模式。「} – muhammad

+0

如果更改應用程序池使用集成應該消失,不知道爲什麼它需要。 –

0

試試下面的方法,並檢查你在控制檯日誌了。

function processChechBox(id) { 
//here is the javascript function for checkbox onChange event 
debugger; 

var containerRef = document.getElementById(id); 
var data = document.getElementById(id); 
data.value = '1'; 
data.checked = true; 

var list = <%= new JavaScriptSerializer().Serialize(Session["chk"]) %>; 
console.log(list); 

}

相關問題