title: Caching ASP.NET Menu control
body: <p>I use a System.Web.UI.WebControls.Menu to build and present a user menu. Loading the menu requires considerable database activity and takes about 1.4 seconds, so I am looking for ways to cache the menu across page turns. If I keep a SessionVariable["ThisMenu"] that contains the menu control, the value of ThisMenu is correct across page turns; however, I cannot set the actual control on the page successfully.</p>
  
  <p>If I try this code, it compiles and executes, but nothing appears in the HTML output:</p>
  
  <pre><code>System.Web.UI.WebControls.Menu ctlMasterMenu = (System.Web.UI.WebControls.Menu)GetControl("ctlMasterMenu");
  if (ctlMasterMenu != null)
  {
      if (ThisMenu != null)
      {
          ctlMasterMenu = ThisMenu;
      }
      else
      {
          LoadPageMenu((System.Web.UI.WebControls.Menu)ctlMasterMenu); // Sets ThisMenu
      }
  }
  
  If I try this code, it executes, but as it adds a MenuItem to ctlMasterMenu, it removes the item from ThisMenu. The result is that after a few page turns, the menu is empty.
  
  System.Web.UI.WebControls.Menu ctlMasterMenu = (System.Web.UI.WebControls.Menu)GetControl("ctlMasterMenu");
  if (ctlMasterMenu != null)
  {
      if (ThisMenu != null)
      {
          List&lt;MenuItem&gt; items = new List&lt;MenuItem&gt;();
          for (int i = 0; i &lt; ThisMenu.Items.Count; i++)
          {
              items.Add(ThisMenu.Items[i]);
          }
          ctlMasterMenu.Items.Clear();
          foreach (MenuItem item in items)
          {
              ctlMasterMenu.Items.Add(item); // Causes item to be removed from ThisMenu
          }
      }
      else
      {
          LoadPageMenu((System.Web.UI.WebControls.Menu)ctlMasterMenu);
      }
  }
  </code></pre>
  
  <p>There must be a simple way that works.</p>