views:

841

answers:

2

I got a simple page with a HtmlInputHidden field. I use a javascript to update that value and when posting back the page i want to read the value of that HtmlInputHidden field.

The Value property of that HtmlInputHidden field is on postback the default value (the value it had when the page got created, not the value reflected through the javascript).

I also tried to Register the HtmlInputHidden field with ScriptManager.RegisterHiddenField(Page, "MyHtmlImputHiddenField", "initialvalue") but it still only lets me read the 'initialvalue' even though i (through javascript) can inspect that the value has changed.

+1  A: 

You ideally want to use the asp.net HiddenField control

<asp:HiddenField id="myHiddenField" runat="server" />

Then you will be able to read the value from the code behind when the page is processing.

string value = myHiddenField.Value; // retrieve the value in hidden field

ref; HiddenField Web Server Control Overview

  • Be careful about the DOM name of the control (control.ClientID) on the client side (ie when you are accessing from javascript) as it may change depending where on the page you have declared the control.
Robert Paulson
Good post you made. I actually did all the above but i forgot to set enableviewstate="true" ;)
Per Hornshøj-Schierbeck
Come to think of it - i didn't actually use the asp:HiddenField - i used the HTMLInputHidden which is not a "pure" asp.net control. I'm sure your example would work as well, since all (afaik? asp:controls have enableviewstate set to true by default)
Per Hornshøj-Schierbeck
+2  A: 

The input field needs to be within a form. Also make sure ViewState is enabled.

leppie
Thanks - i forgot only certain controls (and no HTML-controls) have enableviewstate set to true by default :)
Per Hornshøj-Schierbeck