开发者

User Control's Viewstate

开发者 https://www.devze.com 2022-12-10 12:13 出处:网络
In some book I\'ve seen that they save custom properties of user control like this: private int id = 0;

In some book I've seen that they save custom properties of user control like this:

 private int id = 0;
   public int ID
   {
      get { return id; }
      set { id = value; }
   }

   protected void Page_Init(object sender, EventArgs e)
   {
      this.Page.RegisterRequiresControlState(this);
   }

   protected override void LoadControlState(object savedState)
   {
      object[] ctlState = (object[])savedState;
      base.LoadControlState(ctlState[0]);
      this.ID = (int)ctlState[1];
   }

   protected override object SaveControlState()
   {
      object[] ctlState = new object[开发者_如何学Go2];
      ctlState[0] = base.SaveControlState();
      ctlState[1] = this.ID;
      return ctlState;
   }

My question is why can I simply store it (in setter) in viewstate like: Vistate["ID"]=id;

and then retrieve it form there?


There is a difference between ViewState (what you are talking about in your question) and ControlState (what is shown in the sample code):

  • ViewState can be turned off by the user of your UserControl, by setting EnableViewState="false". In that case, you wouldn't be able to restore your property's value during the next request/postback (because there is no ViewState).
  • ControlState cannot be turned off. This means, that whatever you store in ControlState will be available during the next postback and you should therefore use ControlState for data that you absolutely need to be able to retrieve during the next request/postback.

See also these pages in MSDN: ASP.NET ViewState Overview and ControlState vs. ViewState

Excerpt from the first page:

In addition to view state, ASP.NET supports control state. The page uses control state to persist control information that must be retained between postbacks, even if view state is disabled for the page or for a control. Like view state, control state is stored in one or more hidden fields.

0

精彩评论

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