Monday, March 8, 2010

Access dynamically created javascript elements in code behind

For the longest time I wondered why Asp.net would not provide a mechanism to access elements I had created dynamically using javascript in my code behind. It turns out they do, its just that since we hardly ever use that feature any more (and are more used to accessing elements by their ID’s after dragging and dropping them) it has vanished.

What I was attempting to do was create an input box using javascript, fill it with details and post it back to the server.

Code to create the input box and place it in a div:


function addtb()
{
var getdiv = document.getElementById('holddiv');
getdiv.innerHTML = getdiv.innerHTML + "";
count++;
}



On the code behind though, rather than accessing it using the id/name directly (you cannot do something like [input-box-id].Text = ’some text’) you have to get its value from the Request variable and use the data.



string c = Request.Form["tbs"].ToString();



Also if you wanted it to get displayed on the page the next time around you would have to recreate the elements manually in c#




TextBox t = new TextBox();
t.ID = f;
t.Attributes.Add("name", "tbs");
t.Text = f;
Page.Form.Controls.Add(t);


Although this is cumbersom, it works. I’m not sure if there is an easier way to accomplish this.

No comments:

Post a Comment