Access Viewstate across pages in ASP.NET


Introduction

There was one question during my recent work in one of my ASP.NET Project.

“Is it possible to access the ViewState variable of one page on another page?”

My answer was “No” . Because i have read in books that Viewstate is page specific, it is available only on the same page on which it was created.Once you redirect to another page, the previous page’s viewstate is no longer accessible.

But that is not true. Yes, we can access the viewstate variables across pages. This is only possible if Cross Page Posting or Server.transfer is used to redirect the user to other page. If Response.redirect is used, then ViewState cannot be accessed across pages.

Let us create one sample application to understand this.

Step 1 : Create two page one.aspx & two.aspx

Step 2 : Code for one.aspx.cs

    protected void Page_Load(object sender, EventArgs e)
    {
        ViewState["Page1"] = "Page1 ViewState";
        Server.Transfer("two.aspx");
    }

    public StateBag ReturnViewState()
    {
        return ViewState;
    }

As you can see, I have set a ViewState variable in Page Load and transfer the user to two.aspx page using the Server.transfer() method. This page also contains a method ReturnViewState() which actually returns the ViewState of this page to the calling function. The return type of the method is StateBag class.

StateBag class: This class is the primary storage mechanism for all HTML and Web server controls. It stores attribute/value pairs as strings associated with the control. It tracks changes to these attributes only after the OnInit method is executed for a page request, and saves the changes to the page’s or control’s viewstate.

Step 3 : Code for two.aspx.cs

    private StateBag PreviousPageViewState
    {
        get
        {
            StateBag returnValue = null;
            if (PreviousPage != null)
            {
                Object objPreviousPage = (Object)PreviousPage;
                MethodInfo objMethod = objPreviousPage.GetType().GetMethod
						("ReturnViewState");
                return (StateBag)objMethod.Invoke(objPreviousPage, null);
            }
            return returnValue;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (PreviousPage != null)
        {
            if (PreviousPageViewState != null)
            {
                Label1.Text = PreviousPageViewState["Page1"].ToString();
            }
        }
    }

Whenever we use Server.transfer or Cross Page Posting, We can get the previous page object via PreviousPage property. Using Previous Page, we can find the controls of the previous page. For example, one can access Label control placed in ViewStateContainer Page in current Page.

Looking at the code, I have created a PreviousPageViewState property in this page, which returns the previous page’s ViewState. It first checks whether PreviousPage is null or not, if it’s not null, then it creates an object of the previous page.

Now using Reflection, we can invoke the method of the previous class. Using MethodInfo class, I have invoked the ReturnViewState() method of ViewStateContainer Page.

In Page_Load event, I am able to access the ViewState variable of ViewStateContainer Page. You can access all the viewstate variables set in ViewStateContainer Page.

Step 4: Run the application & see the effect

Recently I got comment from Bijayani & he has highlighted one of the important point regarding  “Viewstate”. so here I am sharing with you.

A Tip While Using ViewState

View state maintains data in a page across postbacks. And this data passes in form of hidden field data. There is a certain limitation of this hidden field. If your hidden field will be greater than that specified value, then sometimes firewalls and proxy servers refuse to let your data passes through. And in that case you have to disable your view state .This might cause many problem if you want your data to be passed.

So to overcome this problem you can do viewstate chunking. This is a process of splitting the data into multiple chunks and putting them into multiple hidden fields, So that there will not be any problem to your data to pass through. This chunking is done by  adding “MaxPageStateFieldLength” property in the page tag in web.config file. The default value is -1 which indicates there is no maximum limit of data. You have to give the integer value which indicates the maximum bytes size for a viewstate field.

For more detail visit this link:
http://www.mindfiresolutions.com/a-tip-while-using-viewstate-548.php

Hope this will helps

Jay Ganesh

Shout it kick it on DotNetKicks.com

About these ads

6 thoughts on “Access Viewstate across pages in ASP.NET

  1. Hi,

    I happened to see your post and find it quite informative. I wanted to share a tip on “Viewstate” which is as follows:

    A Tip While Using ViewState

    View state maintains data in a page across postbacks. And this data passes in form of hidden field data. There is a certain limitation of this hidden field. If your hidden field will be greater than that specified value, then sometimes firewalls and proxy servers refuse to let your data passes through. And in that case you have to disable your view state .This might cause many problem if you want your data to be passed.

    So to overcome this problem you can do viewstate chunking. This is a process of splitting the data into multiple chunks and putting them into multiple hidden fields, So that there will not be any problem to your data to pass through. This chunking is done by adding “MaxPageStateFieldLength” property in the page tag in web.config file. The default value is -1 which indicates there is no maximum limit of data. You have to give the integer value which indicates the maximum bytes size for a viewstate field.

    ………………………….

    After verifying the amount of data you may prefer to do viewstate

    For more detail visit this link:

    http://www.mindfiresolutions.com/a-tip-while-using-viewstate-548.php

    Hope you find it useful and of assistance.

    Thanks for sharing a valuable post.
    Bijayani

    1. Hi Radhika ,
      When you are trying to access a member of a class without instance object you will get Object reference not set to an instance of an object error.So ensure that you are accessing the members with the instance of the class.

      Try to debug your code & identify the cause of error, i am pretty sure you will able to get your answer.

      Thanks
      Sandeep Ramani

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