What do you do when you can't use ViewState?

后端 未结 7 1792
长发绾君心
长发绾君心 2021-02-09 06:43

I have a rather complex page that dynamically builds user controls inside of a repeater. This repeater must be bound during the Init page event before ViewState is

7条回答
  •  死守一世寂寞
    2021-02-09 07:15

    The LoadViewState method on the page is definitely the answer. Here's the general idea:

    protected override void LoadViewState( object savedState ) {
      var savedStateArray = (object[])savedState;
    
      // Get repeaterData from view state before the normal view state restoration occurs.
      repeaterData = savedStateArray[ 0 ];
    
      // Bind your repeater control to repeaterData here.
    
      // Instruct ASP.NET to perform the normal restoration of view state.
      // This will restore state to your dynamically created controls.
      base.LoadViewState( savedStateArray[ 1 ] );
    }
    

    SaveViewState needs to create the savedState array that we are using above:

    protected override object SaveViewState() {
      var stateToSave = new List { repeaterData, base.SaveViewState() };
      return stateToSave.ToArray();
    }
    
    
    

    Don't forget to also bind the repeater in Init or Load using code like this:

    if( !IsPostBack ) {
      // Bind your repeater here.
    }
    

    提交回复
    热议问题