What are the possible situations where the .net Viewstate might stop working?

Consider the following code:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        If Page.IsPostBack Then
            If ViewState("test") IsNot Nothing Then
                Response.Write((ViewState("test").ToString))
            Else 
                Response.Write("Viewstate is empty.")
            End If
        Else
            ViewState("test") = "viewstate is working."
        End If
    End Sub

      

This code doesn't work on a specific page of my application. Viewstate is not disabled in the Page directive. I can't figure out what's going on.: \

Oh, I just figured it out. See if you noticed it.

<.

+1


source to share


5 answers


It turned out someone changed the Page_Load event to handle the .Init page



Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

      

+3


source


You can also disable browsing from the config file.



<configuration>
  <appSettings>
    <Pages EnableViewState="false" />
  </appSettings>
</configuration>

      

+1


source


Are you sure you did the postback?

Should "Viewstate is empty" be recorded? Or just nothing?

+1


source


Since you didn't reply to your own post ...

I would say that you are checking IsPostBack and accessing the ViewState at the wrong stages:

Handles Me.Init

      

It should be

Handles Me.Load

      

right?


For debugging headaches like this in ASP.NET, I would also like to add that tracing often helps.

You can enable tracing by adding this to your web.config:

<configuration>
  <system.web>
    <trace enabled="true" pageOutput="true" requestLimit="40" localOnly="false"/>
  </system.web>
</configuration>

      

This will add a stack trace and not yet the end of each page, so you can trace back and (hopefully) figure out the problem.

+1


source


In my case, I was writing data to ViewState on page_Init. This data was displayed on the Page_Load and Page_PreRender pages, but was not persisted on the page at the end of the lifecycle. After the postback ViewState was empty.

So, make sure you write in ViewState AFTER Page_Init.

+1


source







All Articles