About Links Archives Search Feed Albums of Note

Postback or refresh

Came across an interesting case a few days ago to do with ViewState. (OK, I know some people will say don’t use ViewState ever, but humour me)

Create a page on it with two buttons and a label, which we’ll call lblCounter.

The codebehind this page is a follows

Protected Sub Button2_Click( ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click Response.Redirect(“AnotherPage.aspx”) End Sub Protected Sub Page_Load(

ByVal sender As Object, ByVal e As System.EventArgs)

Handles Me.Load

ViewState(“Counter”) += 1

lblCounter.Text = ViewState(“Counter”).ToString()

End Sub

Run this little page and, as you would expect, the counter returns 1.

Now for the interesting bit. Hit button 1 a few times and then click refresh on your browser. You get a dialog asking if you want to resend the information to get the page in order to refresh it.

The clue is in the text of the dialog. It is resending the information used to bring this instance of the page into the browser. Let’s suppose the counter on the page is set to 4. When refresh is pressed, all the http post data, which includes the ViewState from the previous instance of the page (counter = 3) is sent to the server again and when the server runs Page_Load it gets handed the previous value of the counter (3, not 4 as you might expect) and increments it as instructed in Page_Load (to 4 and not 5).

Posted on June 22, 2007   #Geek Stuff  

← Next post    ·    Previous post →