Working with hidden variables in ASP.NET 1.1 and 2.0
While working on an ASP.NET page I had to read and write some hidden variables in my code behind.
I figured I could use the following:
Page.RegisterHiddenField(”test”, “testvalue”);
This would create a hidden variable in my HTML which I should be able to access with JavaScript like this:
document.getElementById(’test’).value
The task seemed easy, and I figured it would take around 10 minutes to get everything working. Only there was one problem. The hidden field was rendered like this:
<input type=”hidden” value=”testvalue” />
What is the problem here? Id and/or name are missing! And because of it, I cannot access this variable in my JavaScript.
What is the solution? Use HtmlInputHidden. Here is how to use it.
<input type=”hidden” id=”test” runat=”server” />
And in your code-behind you can assign correct values:
test.Value = “testvalue”
Make sure that the HtmlInputHidden is registered.
protected HtmlInputHidden test;
Now, I encountered this problem in ASP.NET 1.1; In ASP.NET 2.0 this problem has been resolved. Using Page.RegisterHiddenField will produce something similar to this:
<input id=”test” name=”test” type=”hidden” value=”testvalue” />
But, Page.RegisterHiddenField is marked as obsolete, so you can still use it, but it is not recommended. What is the recommended solution?
ClientScriptManager.RegisterHiddenField(string hiddenFieldName, string hiddenFieldInitialValue)
This is the recommended way to work with hidden variables in ASP.NET 2.0. To find out more information - http://msdn2.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerhiddenfield.aspx
2 Comments so far
Leave a reply
Thanx..
It resolved my Problem
I tried a web solution of passing JS hidden variable to ASPX, but the value passed by JS is not recieved at C# server side.
the code is below here. Please help.
Quote:
protected void Button2_Click(object sender, EventArgs e)
{ Label2.Text =”received .” + rect.Value +” ” + rect.Type;
//rect.Value not showing up anything
}
document.Form1.rect.value =”Doesn’t work! Please help”;
js to asp.net Test
Finally I want ot pass a hidden var for C# System.Drawing.Rectangle object.
Please help.