Wednesday, March 16, 2005

ASP.NET's RegisterHiddenField and document.getElementById

I was doing some testing today to find out why one of our ASP.NET web apps wasn't working in Firefox. It boiled down to the fact that ASP.NET's Page.RegisterHiddenField() method doesn't set the 'id' attribute of the element it creates, only the 'name' attribute. This in turn breaks Firefox's getElementById because in Firefox (and all other Mozilla-based browsers, as I understand) the id and name namespaces are not merged (as they are in IE). So getElementById() in Firefox will never find a hidden element created by using RegisterHiddenField().

The simple workaround is to use a HTML Hidden Input element as follows in the ASPX page:

<input type="hidden" id="myHiddenElement" runat="server" value="myvalue" />

Then in the .cs codebehind you can declare your hidden element as follows:

protected System.Web.UI.HtmlControls.HtmlInputHidden myHiddenElement;

and you can manipulate the control in the codebehind as follows:

this.myHiddenElement.Value = "some value";

I would consider this a bug in the RegisterHiddenField() but if someone can explain why it isn't, I'd LOVE to hear why.


Eva Rossa said...

Thank you for this code, works fantastically well for me! Been searching for this for 2 nights! *kiss*

Don Draper said...

Yes, having a similar problem although not in ASP, not ASP.NET. Gotta go add those ID attributes to my tags. Thanks very much.

Anonymous said...

Thanks alot!. I searched google for "firefox getelementbyid" and this was the first page that came up. Solved my problem in two seconds. I am just trying to fixup an old html webpage so it works in firefox. Thanks again.

Anonymous said...

a little mistypo but .value should be .Value

andy said...

just got into this problem recently, i usually declared these hidden fields as member but this time it's a bit different - i needed only 1 instance of the field in the whole page hence "RegisterHiddenField" was a must (for being the easiest solution rather than custom work-arounds). the hack that could be used is something like this RegisterHiddenField("myField\" id=\"myFieldId\"", "initialValue"); and good thing ASP.Net didn't care to "validate" the name :)

Marc said...

Looks like this has been fixed in .Net 2.0

Anonymous said...

Another alternative:

var x = getElementsByName();

Then access the element's value like this:

var y = x[0].value;