views:

374

answers:

6

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 particular page in my application. Viewstate is not turned off in the Page directive. I can't figure out what's going on. : \

Oh i just figured it out. See if you notice it.

.<

+1  A: 

You can turn off viewstate from the config file too.

<configuration>
  <appSettings>
    <Pages EnableViewState="false" />
  </appSettings>
</configuration>
i voted up but its not the issues a viewsstate tag is actually getting rendered on the page. i feel like im going insane here.
Shawn Simon
A: 

Could you post more code from the page?

How do you trigger the postback? a simple button?

chakrit
thers a ton of code and it works fine in another app. the code is owned by the company i work for. anyway the stuff you posted would throw a cast exception because viewstate is an object and string.isnullorempty expects a string.
Shawn Simon
Removed the code...
chakrit
+1  A: 

Are you SURE that you make a postback?

Do it write "Viewstate is empty"? Or just nothing?

Jesper Blad Jensen aka. Deldy
+3  A: 

Figured it out, someone had changed the Page_Load event to handle Page.Init

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
Shawn Simon
don't you hate those?
Tom Anderson
+1  A: 

Since you didn't answer your own post...

I'd say you are checking IsPostBack and accessing ViewState at the wrong stages:

Handles Me.Init

That should be

Handles Me.Load

right?


For debugging such headaches in ASP.NET I'd also like to add that tracing can often helps a lot.

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

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

This will append the stack trace and whatnot to the end of every page, so you can trace the execution and (hopefully) find out the problem.

chakrit
Doh!... I've got to be faster next time...
chakrit
+1  A: 

In my case I was writing data to a ViewState on Page_Init. This data was displaying nice on Page_Load and Page_PreRender, but it was not being persisted to page at the end of life-cycle. After postback ViewState was empty.

So, make sure that you write to ViewState AFTER Page_Init.

Monsingor