Tuesday, July 27, 2010

Working with Hidden Fields in ASP.NET

I need to use old school HTML hidden fields in a webpage I'm making because I need to pass it as a post parameter to an external server. I tried using the .NET server controls (ie. runat='server') but realized later that it mangles the name. So by the time the external server receives it, the names has some gibberish prefix or suffix.

Next I tried using the Visual Studio standard html hidden fields control but found out that they cannot be accessed from Code Behind. Since I need to set the hidden field values dynamically at runtime, and not at design time, that's a bit of a problem. The way I used to do it is to use the .NET Literal text control. I would put the Literal control on the page and set its value to the actual html code of "input type=hidden..." during runtime. Not a very efficient method.

After doing some more research, I found a way to dynamically insert hidden fields programmatically through the Page class:

this.Page.ClientScript.RegisterHiddenField(fieldname, fieldvalue)

That solved my problem!

No comments: