ascx viewstate null when inside hidden PlaceHolder

95 views Asked by At

I have a custom user control ascx that exposes a simple property

    /// <summary>
    /// The currently selected ID, if there is one
    /// </summary>
    public virtual int? SelectedId
    {
        get { return (int)ViewState["XXID"]; }
        set { ViewState["XXID"] = value; }
    }

The control is inside a PlaceHolder and the value reads just fine in the postback onclick method of a button below the PlaceHolder.

However if the PlaceHolder visible=false then ViewState["XXID"] returns null. If I toggle the PlaceHolder visible=true then the value comes back.

    <asp:PlaceHolder runat="server" ID="plcCustomer" >
        <my:CustomPicker runat="server" ID="cboCustomer" />
    </asp:PlaceHolder >
    <asp:Button runat="server" ID="btnToggleVisible" onclick="btnToggleVisible_OnClick" text="Toggle visible" />
    <asp:Button runat="server" ID="btnGetSelectedId" onclick="btnGetSelectedId_OnClick" text="Get Value" />

    protected void Page_Load(object sender, EventArgs e)
    {
       if (!IsPostBack)
          plcCustomer.SelectedId = 5;
    }
    protected void btnToggleVisible_OnClick(object sender, EventArgs e)
    {
       plcCustomer.Visible = !plcCustomer.Visible;
    }
    protected void btnGetSelectedId_OnClick(object sender, EventArgs e)
    {
       ...
       plcCustomer.SelectedId //<== this will be null whenever plcCustomer is invisible
       ...
    }

I have a hunch that the page has not bothered loading my control's viewstate because it is not going to be visible.

If so how can I instruct the page that it should load the viewstate of custom controls even when they are in a hidden PlaceHolder?

0

There are 0 answers