R – How to persist the value of a label through a response.redirect

asp.netpersistenceviewstate

Here's the situation: I have a label's text set, immediately followed by a response.redirect() call as follows (this is just an example, but I believe it describes my situation accurately):

aspx:

<asp:Label runat="server" Text="default text" />

Code-behind (code called on an onclick event):

Label.Text = "foo";
Response.Redirect("Default.aspx");   

When the page renders, the label says "default text". What do I need to do differently? My understanding was that such changes would be done automatically behind the scenes, but apparently, not in this case. Thanks.

For a little extra background, the code-behind snippet is called inside a method that's invoked upon an onclick event. There is more to it, but I only included that which is of interest to this issue.

Best Answer

After a redirect you will loose any state information associated to your controls. If you simply want the page to refresh, remove the redirect. After the code has finished executing, the page will refresh and any state will be kept.

Behind the scenes, this works because ASP.NET writes the state information to a hidden input field on the page. When you click a button, the form is posted and ASP.NET deciphers the viewstate. Your code runs, modifying the state, and after that the state is again written to the hidden field and the cycle continues, until you change the page without a POST. This can happen when clicking an hyperlink to another page, or via Response.Redirect(), which instructs the browser to follow the specified url.