ASP.NET HiddenField Values Modified By JavaScript Not Being Persisted During Postback

Here's a quick fix to a problem I ran into today: I have a UserControl in .NET which includes a HiddenField control. I use a JavaScript function to modify the value of the control (getting the control with document.getElementById() and passing in the ClientID of the HiddenField control), and then make use of the value later in my server side code during postbacks.

The problem I ran into was that the value wasn't being persisted -- however, it used to work.

I realized that because I had moved the code that made use of this value into the Page_Init event handler a short time earlier, this had broken the functionality. I moved it to Page_Init because I'm doing dynamic control creation, and I've read in countless places that the preferred location for this is Page_Init. Moving this code back to Page_Load corrected the issue -- in the ASP.NET Page Lifecycle, the controls values have not been restored from ViewState during Page_Init.


Anonymous said…
Four days I looked at this problem. I moved to OnInit because of a syntax error I didn't notice because as you say this is the recommended path.

After reading this I moved it back with the correct syntax and it works.

Cheers mate. You are a legend.

Popular posts from this blog

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

"$.ajax is not a function" Error When Using jQuery and Darren Johnstone's ASP.NET Upload/Download Module v2