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:
C#:
string script = string.Format("localStorage.clientId = '{0}';", _MySession.CurrentClientId);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "key", script, true);
(see: this SO question)
To get the data back from localStorage to code-behind, the asp.HiddenField
element seems to be made for this: the element can easily be written with JavaScript and can be read from code-behind:
HTML:
<asp:HiddenField ID="hf_ClientId" runat="server" />
JS:
document.getElementById("<%=hf_ClientId.ClientID%>").value = localStorage.clientId;
code-behind, C# (in a MasterPage):
var v = hf_ClientId.Value;
However, the code-behind is in Page_Load, and runs before the html is constructed and the JS is run in $(document).ready, so no value is received.
Then I tried to move the JS to theForm.onsubmit
which is run as a hook by __doPostBack
. 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.
What am I doing wrong and how to fix this?