2012-04-10 35 views
2

如何訪問由JavaScript動態創建的控件(在CodeBehind中)的值?如何訪問代碼隱藏控件的值,這是由javascript動態創建的

我創建控件動態使用下面的代碼:

var counter = 0; 
var words; 
var foo;//span tag 

function add(i) { 
    var counter = 0; 
    var words; 
    var foo;//span tag asp in page where the controls to be added 

    if (i == 'ad') { 
     counter++; 
     //Create an input type dynamically. 
     foo = document.getElementById("dynamic") 
     tbnam = document.createElement("input") //textbox 
     tbdes = document.createElement("input") //textbox 
     lbnam = document.createElement("Label") 
     lbdes = document.createElement("Label") 
     before = document.createElement('br') 
     after = document.createElement('br') 

     //Assign different attributes to the element. 
     wordsnam = document.createTextNode("Item") 
     wordsdes = document.createTextNode("Descrip") 
     tbnam.setAttribute("type", "TextBox"); 
     tbdes.setAttribute("type", "TextBox"); 
     tbnam.setAttribute("Id", "tbdynamicnam" + counter); 
     tbdes.setAttribute("Id", "tbdynamicdes" + counter); 
     lbnam.setAttribute("Id", "lbdynamicnam" + counter); 
     lbdes.setAttribute("Id", "lbdynamicdes" + counter); 
     before.setAttribute("Id", "bf" + counter); 
     after.setAttribute("Id", "af" + counter); 

     lbnam.appendChild(wordsnam) 
     lbdes.appendChild(wordsdes) 

     //Append the element in page (in span). 

     foo.appendChild(before); 
     foo.appendChild(lbnam); 
     foo.appendChild(tbnam); 
     foo.appendChild(lbdes); 
     foo.appendChild(tbdes); 
     foo.appendChild(after);    
    } 
} 

回答

6

當提交表單時它會在Request.Form collection,您可以訪問它Request對象,這將檢查所有藏品最簡單的(查詢字符串,表單,Cookie和ServerVariables)

的JavaScript:

tbnam = document.createElement("input") //textbox  
tbnam.setAttribute("type", "TextBox");  
tbnam.setAttribute("Id", "tbdynamicnam" + counter); 
tbnam.setAttribute("name", "tbdynamicnam" + counter); 

代碼隱藏:

string newval = Request["newelementname"]; 

正如James Montagne下文提到的,你需要一個表單元素名稱。

+0

而你需要給元素一個名字。 – 2012-04-10 14:19:47

+0

如果您想在提交表單之前訪問,則不可能 – levi 2012-04-10 14:21:11

+1

+1:值得注意的是,這僅適用於輸入。 – 2012-04-10 14:25:39

相關問題