This has nothing to do with ViewState. A form control's value is maintained by doing a POST. As long as the control is created early enough in the page lifecycle, the posted value will be set on the control. If you refresh the page or click on a hyperlink that does a GET, then the value will be lost or revert to the designer-generated default.
Back to your question, if you have a designer-generated HiddenField
(in the aspx file), it should automatically set the value on postback. Either you're changing it somewhere else in your code or you are trying to access the value before it has been set (i.e. before Page_Load()
). If you have a code-generated HiddenField
, it needs to have the same ID and be created before the Page sets the posted values, such as in OnInit
.
I would recommend you read through and understand the following articles. Otherwise, you will keep hitting walls because the Page lifecycle and ViewState are fundamental.
http://msdn.microsoft.com/en-us/library/ms972976.aspx
http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…