title: which loading event to use for assigning to Asp.Net HiddenField
body: <p>I need to get a value (ClientId) from localStorage to code-behind. This is handy for logging in with a 'client' setting from a previous session, stored with:</p>
  
  <p>C#:</p>
  
  <pre><code>string script = string.Format("localStorage.clientId = '{0}';", _MySession.CurrentClientId);
  Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "key", script, true);
  </code></pre>
  
  <p>(see: <a href="https://stackoverflow.com/questions/24250758/setting-a-value-to-a-hiddenfield-in-asp-net-4-5/24251368">this SO question</a>)</p>
  
  <p>To get the data back from localStorage to code-behind, the <code>asp.HiddenField</code> element seems to be made for this: the element can easily be written with JavaScript and can be read from code-behind:</p>
  
  <p>HTML:</p>
  
  <pre><code>&lt;asp:HiddenField ID="hf_ClientId" runat="server" /&gt;
  </code></pre>
  
  <p>JS:</p>
  
  <pre><code>document.getElementById("&lt;%=hf_ClientId.ClientID%&gt;").value = localStorage.clientId;
  </code></pre>
  
  <p>code-behind, C# (in a MasterPage):</p>
  
  <pre><code>var v = hf_ClientId.Value;
  </code></pre>
  
  <p>However, the code-behind is in Page_Load, and runs <em>before</em> the html is constructed and the JS is run in $(document).ready, so no value is received.</p>
  
  <p>Then I tried to move the JS to <code>theForm.onsubmit</code> which is run as a hook by <code>__doPostBack</code>. With the Firefox F12 debugger and the VisualStudio C# debugger I verified that the JS is called before the C# as soon as a postback occurs by clicking some button on the form, but still no value received there.</p>
  
  <p>What am I doing wrong and how to fix this?</p>