1

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?

Martin Belcher - AtWrk
  • 4,579
  • 4
  • 33
  • 41
  • Does this help https://forums.asp.net/t/1648528.aspx ? or this https://stackoverflow.com/questions/27483486/register-viewstate-for-visible-false-usercontrol-asp-net? – Tarun Lalwani Mar 19 '18 at 08:11
  • No @TarunLalwani sorry that did not help. However I have a workaround, never set PlaceHolder visible=false, instead leave it visible so that its HTML is always sent to the browser then hide that with CSS classes client side. That means all the viewstate is preserved and still achieves the required result of hiding content. Drawback is larger HTTP traffic. – Martin Belcher - AtWrk Mar 21 '18 at 14:10

0 Answers0