UserControl Viewstate loses all values after postback

35,651

Your code works perfectly here. The only explanation I can think of is that the ViewState is disabled on a parent control. JournalRanking is inside a page which is inside a MasterPage. Check that you don't have EnableViewState=false anywhere because that would prevent you to retrieve the value on the page postback.

Share:
35,651
user467384
Author by

user467384

Updated on May 07, 2020

Comments

  • user467384
    user467384 about 4 years

    I have a user control on a page that needs to persist some state in viewstate. Whenever a postback happens the entries in the viewstate get set to null.

    Page

    <%@ Page Title="" Language="C#" MasterPageFile="~/Main.master" %>
    <%@ Register TagPrefix="JR" TagName="JournalRanking" Src="~/Controls/JournalRankRadioButton.ascx" %>
    <script runat="server">
    </script>
    
    <asp:Content ID="Content3" ContentPlaceHolderID="Content1placeholder" Runat="Server">
        <asp:Panel CssClass="insetBG1" ID="FormView1" runat="server">
            <JR:JournalRanking ID="JournalRanking1" runat="server" ViewStateMode="Inherit" />
        </asp:Panel>
    </asp:Content>
    

    User Control

    <%@ Control Language="C#" ClassName="JournalRankRadioButton" %>
    <script runat="server">    
        public String Test
        {
            get
            {
                if (ViewState["Test"] == null)
                {
                    ViewState["Test"] = String.Empty;
                }
                return ViewState["Test"].ToString();
            }
            set
            {
                ViewState["Test"] = value;
            }
        }
    
    public void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            this.Test = "Test";
        }
    }
    </script>
    <asp:CheckBox runat="server" AutoPostBack="true" />
    

    When I load the page, ViewState["Test"] gets assigned to "Test", but when I check the checkbox, the page does a postback and ViewState["Test"] is null again. What am I missing?

    -Update-

    So, even though I was setting EnableViewState = true in the page and the control EnableViewState was false in the master page. I had to add

    this.Page.Master.EnableViewState = true;
    

    to the Control to get it to work.

    Thanks for the help!

  • user467384
    user467384 about 11 years
    The EnableViewState was false in the master page (though I couldn't find where it was set explicitly). Setting it to true in the Control fixed the issue.