title: Keeping the Viewstate persistent and retrieve it on demand
body: <p>I've got a page with several controls, such as Checkboxlists and two containers holding search results.</p>
  
  <p>I've been told to make this site persistent, so the user can come back from anywhere while browsing our site and find it's settings restored (read: boxes stll checked; results still available)</p>
  
  <p>So far I have tried to override SavePageStateToPersistenceMedium and LoadPageStateFromPersitenceMedium, but I am constantly running into a yellow screen of death as soon, as I click a button on the page.</p>
  
  <pre><code>protected override void SavePageStateToPersistenceMedium(object viewState)
  {
      string str = "VIEWSTATE_" + Request.UserHostAddress;
      Cache.Add(str, viewState, null, DateTime.Now.AddMinutes(Session.Timeout), TimeSpan.Zero, CacheItemPriority.Default, null);
      ClientScript.RegisterHiddenField("__VIEWSTATE_KEY", str);
      ClientScript.RegisterHiddenField("__VIEWSTATE", "");
  }
  protected override object LoadPageStateFromPersistenceMedium()
  {
      string str = Request.Form["__VIEWSTATE_KEY"];
      if (!str.StartsWith("VIEWSTATE_"))
      {
          throw new Exception("Invalid viewstate key:" + str);
      }
      return Cache[str];
  }
  </code></pre>
  
  <p>Is there anything wrong with my code and what would I need to call to retrieve the Viewstate on Page_Load or Page_init to retrieve it?</p>
  
  <p>edit:
  Here is the approach to solve it via session["xyz"]</p>
  
  <pre><code>List&lt;ListItem&gt; selectItems = new List&lt;ListItem&gt;();
          foreach (ListItem item in CheckBoxListLevel.Items)
          {
              if (item.Selected)
                  selectItems.Add(item);
          }
  
          Session.Add("SavedLevelItems", selectItems);
  </code></pre>
  
  <p>//And then in Page_Load</p>
  
  <pre><code>   if (Session["SavedLevelItems"] != null)
      {
          List&lt;ListItem&gt; SessionList = (List&lt;ListItem&gt;)Session["SavedLevelItems"];
          foreach (var item in SessionList)
          {
              if (item.Selected)
              {
                  CheckBoxListLevel.Items.FindByText(item.Text).Selected = item.Selected;
              }
          }
      }
  </code></pre>
  
  <p>However, if I view a searchresult and then just fire a GET to get back to the initial page, all stored items are not rendered correctly.</p>