开发者

Page cycle and viewstate problem

开发者 https://www.devze.com 2022-12-09 23:48 出处:网络
Need help with lifecycle of page. When I have a button it\'s click handler stores a value in ViewState.

Need help with lifecycle of page.

When I have a button it's click handler stores a value in ViewState.

When the button is clicked a postback occurs but when if I try to read the viewstate vale in pageload, I get a wrong value.

When page is refreshed it needs to display a label according to the value in viewstate.

Page_Load is not a right p开发者_JAVA百科lace for that.

In what page event I should display this label?


So the page load events flow as:

  1. Action on form causes Postback
  2. Page_Load Event
  3. Button Click Event
  4. Render/Unload Event

At step 2 you are reading a variable from the viewstate and setting a label. At step 3 you're setting the value in the viewstate.

As you've observed you're using the events in incorrect order. There are two ways you can solve this: Place your label setter code in Render/Unload event. The other is to refactor your code such that the label is set via the Button Click Event instead of in the Page_Load event; which I would recommend as the proper course of action.

You may want to checkout What is the ‘page lifecycle’ of an ASP.NET WebForm? to get a better handle on page lifecycle.


In response to the comment: If there's multiple labels to set you can look at inline code to set your labels. The code would look like this:

CodePage

<asp:Label id="id1" runat="server" text="<%=Label1Text%>" />

CodeBehind

private string m_Label1Text;
public property string Label1Text {
    get { return m_Label1Text; }
    set { m_Label1Text = value; }
}

This way, you set your text via the Label1Text property and it gets transfered to the form when it's rendered. You can try this Tutorial here if you need more information on inlining code.


Page_LoadComplete occurs directly after the control events have been handled, while Page_Load occurs directly before control events.

http://msdn.microsoft.com/en-us/library/ms178472.aspx


The problem you're having is that Page_Load runs before the button click handler, so you get:

  1. Click button
  2. Check Viewstate value (it hasn't been set yet)
  3. Button handler runs and sets Viewstate

You could try Page_Prerender, this should happen after the control handlers are fired.


Override the LoadViewState and SaveViewState methods in your code-behind.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号