Viewstate and controls in ASP.NET

前端 未结 4 608
轮回少年
轮回少年 2021-02-09 01:56

I posted a question a couple of days ago about viewstate and after running some tests I have come to some conclusions/results. Based on these results I have a few questions as t

4条回答
  •  太阳男子
    2021-02-09 02:38

    It is accepted practice to load dynamic controls in OnInit, so that they get the full control lifecycle. I'm not sure I particularly understand your situation though - if you're loading a control based on a button click, why would it have viewstate at that point? On the next OnInit, you should load the control again (I usually use a page level Viewstate item to track that a particular control needs to be loaded) so that it can restore from Viewstate. Something like:

    class Default : Page {
       enum LoadedControl { Textbox, Label, GridView }
    
       override OnInit() {
          if (IsPostback) {
            var c = Viewstate["LoadedControl"] as LoadedControl;
            if (c != null) LoadDynamicControl(c);
          }
       }
    
       void Button_Click() {
         var c = (LoadedControl)Enum.Parse(typeof(LoadedControl), ddl.SelectedValue);
         LoadDynamicControl(c);
       }
    
       void LoadDynamicControl(LoadedControl c) {
         switch (c) {
            case LoadedControl.Textbox:
               this.ph.Controls.Add(new Textbox());
               break;
            ...
         }
    
         ViewState["LoadedControl"] = c;
       }
    }
    

    The slightly more interesting bit, though, is that according to catch-up events - it really shouldn't matter. The callstack for dynamically loading a control looks something like:

    Control.Controls.Add(Control)
       Control.AddedControl(Control)
          Control.LoadViewStateRecursive(object)
              Control.LoadViewState(object)
    

    Taking Label as an example, it overrides LoadViewState and pulls it's Text property directly from ViewState. TextBox is similar. So, by my reading, it should be OK to add at any point, and then access ViewState. That doesn't seem to be jive with my experience, though, so further investigation seems warranted.

提交回复
热议问题