UserControl Viewstate loses all values โ€‹โ€‹after postback

I have a user control on a page that should save state in a viewstate. Whenever a postback occurs, the entries in the view are visible, 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 box, the page performs a postback, and ViewState ["Test"] is again null. What am I missing?

-Update -

So, although I set EnableViewState = true on the page, and the EnableViewState control was false on the main page. I had to add

 this.Page.Master.EnableViewState = true; 

to the Office to make it work.

Thanks for the help!

+6
source share
1 answer

Your code works fine here. The only explanation I can think of is that ViewState is disabled in the parent control. JournalRanking is inside a page inside MasterPage. Make sure you do not have EnableViewState=false anywhere, because this will prevent you from getting the value on the back of the page.

+8
source

Source: https://habr.com/ru/post/944250/


All Articles