How can I save asp:HiddenField value across postback?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
Method 2
Placing and asp:hiddenfield inside an asp:UpdatePanel works.
Method 3
If you are dynamically adding it that will happen if its added too late in the page life cycle. Add it in PreInit and you should be fine. Check out http://msdn.microsoft.com/en-us/library/ms178472.aspx for more info.
Method 4
Yes, asp:HiddenField inside an asp:UpdatePanel works.
Method 5
Set EnableViewState to True
Method 6
By default, it was built to do that. There shouldn’t be an issue there unless you’ve disabled viewstate for the control, a parent control, or the page.
Method 7
It happens due to the update panel please check your update panel. use a single update panel for the whole page.
Method 8
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:HiddenField ID="hdnFld" Value="xyz" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
If you change the hidden fields value using JQuery and after that the page get refreshed, the hidden fields value will be the new value.
now access the same using JQuery.
var currentTab = $('#hdnFld').val();
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0