in

ASP.NET Weblogs

Casey Roach

October 2008 - Posts

  • RegisterHiddenField within dynamically created controls

    I've been building a composite control that has a client-side object associated with it.  Any changes on the client are persisted back to the server through a hidden field and the server-side object is updated with these changes.  I register the hidden field with the page in the OnPreRender event of the control.  This works well with statically created controls.

    I ran into trouble when I was creating these controls dynamically.  My controls were being created and added to the Page on every postback in the Page's OnInit event.  However, when it came time for the control to save its client state in the hidden field, the hidden field couldn't be found!

    What's wrong here? Here is a snippet from my control's code:

    protected override void OnPreRender(EventArgs e)
    {
         ScriptManager sm = ScriptManager.GetCurrent(Page);
         if (sm == null)
         {
              throw new InvalidOperationException("A ScriptManager is required on this page");
         }
         base.OnPreRender(e);
         ClientScript.RegisterHiddenField(this.ClientStateID, "");
    }
    

    Nothing! (at least that's what I thought). See if you can spot the difference in this next snippet:

    protected override void OnPreRender(EventArgs e)
    {
         ScriptManager sm = ScriptManager.GetCurrent(Page);
         if (sm == null)
         {
              throw new InvalidOperationException("A ScriptManager is required on this page");
         }
         base.OnPreRender(e);
         ScriptManager.RegisterHiddenField(this, this.ClientStateID, "");
    }
    

    After cracking open the source code to the AjaxControlToolkit, I saw that the experts were calling the ScriptManager's static method in order to register the hidden field with the page.  I'm not sure why you can't call the Page's ClientScript's method instead, but just in case anyone else runs up against this, I thought I'd throw this out there to help.

More Posts