Context.Items vs. ViewState

To pass values from one page to another, Context.Items and ViewState are used most often.

It is important to keep in mind that values stored in the Context.Items collection only last for the current request. If I were to do a postback on the page, the Context item would be lost. Most of the time this is convienient since we only need to store that value between pages and no longer.

To keep track of values between postback, use ViewState. Unlike Context.Items collection that is used to transfer data from one page to another, ViewState can be only used for the same page. It is useful for postback. Also, Context.Items is used very often in the server farm architecture.

It’s common to use this in the page_load function of the page. Check out the example below. Note that the IsPostBack condition below. If that is not there, then the postback of the page will read Context.Items(“id”) again which will be null. This will cause a problem. That is why it is important to have it there.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim ProductToShow As Integer
If Not Me.IsPostBack Then
ProductToShow = Context.Items("Id")
Me.ViewState("Id") = ProductToShow
Else
ProductToShow = Me.ViewState.Item("Id")
End If
End Sub

Advertisements

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: