1(818)262-8552
Or Email
contact@invertedsoftware.com

Save Your Page State Between Posts To Multiple Pages


By Gal Ratner

ASP.NET 1.0 Introduced the Postback model.
Web Controls are actually objects and can be accessed from the page's code behind in order to set or get attributes.
Web Controls can actually retain their values across multiple round trips (Postbacks) to the server as long as the form on the page posts to the page itself.
In order to insure integrity of the page's form values, the ASP.NET Model uses a hidden encrypted field named __VIEWSTATE.
In addition, the ViewState of the page can be accessed at any time and additional values can be stored.
For Example: ViewState["color"] = "red"; will keep the value "red" for as many postbacks as needed.

ASP.NET 1.0 and 1.1 Models are designed with page encapsulation in mind.
Each page is a self contained object and must contain one form with a self URL as the target.
Many developers have designed their web application with cross posting in mind, meaning, a form rendered on a page can post values to another page, making the website less secure but easier to build in some cases.
This posed another problem. How to retain the original values when revisiting the source page? "Moving" the values from one page to another is not practical. The new page will have a __VIEWSTATE of its own and will not replace it with the _VIEWSTATE that was posted to it. QueryString? The __VIEWSTATE can get very large and QueryStrings are limited in size. .NET 2.0 Comes with an out of the box solution for this problem.

Cross Page PostBack

By setting the PostBackUrl on a Button, LinkButton or ImageButton control, we can post our form to another page. The page can then check if the post accured from a different URL by getting the Page.IsCrossPagePostBack property and even access controls on the previous page by using the Page.PreviousPage property.
This is certainly a leap forward for .NET 2.0 and eliminates any security issues with cross posting. But what happens when we need to retain the original page's state across multiple pages, not just access it from another page.
For example: a search page that has a search state and a details link. Following the link will take us away from the search page. When done editing, we want to navigate away from the details page and back to the search, however we do not want to post back to the search page, but use a direct link.
<a href="Search.aspx">back to the search</a>. in that case the page.PreviousPage.PreviousPage property will not work. There is nothing posted to the search page and yet we still need to retain the original search criteria.

1. A Custom Session based solution (ASP.NET 1.1)

We are going to use the pre render method.
This method is being invoked after the page has been initialized but before it saved its ViewState and rendered.
Are are going to load the Request.Form into a session variable and load it back with each call to the page that is not a postback.

Here is the code:

protected void Page_PreRender(object sender, EventArgs e)
{
  // Save the last search and if there is no new search parameter
  // Load the old viewstate
   if (!Page.IsPostBack && Session["PageState"] != null)
   {
    NameValueCollection formValues = (NameValueCollection)Session["PageState"];

    String[] keysArray = formValues.AllKeys;
    for (int i = 0; i < keysArray.Length; i++)
    {
      Control currentControl = Page.FindControl(keysArray[i]);
      if (currentControl != null)
      {
        if (currentControl.GetType() == typeof(System.Web.UI.WebControls.TextBox)) ((TextBox)currentControl).Text = formValues[keysArray[i]];
        else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.CheckBox))
      {
      if (formValues[keysArray[i]].Equals("on")) ((CheckBox)currentControl).Checked = true;
        }
        else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
((DropDownList)currentControl).SelectedValue = formValues[keysArray[i]].Trim();
      }
    }
  }

  if(Page.IsPostBack) Session["PageState"] = Request.Form;

}

If you have any additional control types on your form, you may add them to the type validation, in fact, you can add as many types as you like as long as the data contained in the control can be kept in a session variable.

2. SessionPageStatePersister (ASP.NET 2.0)

ASP.NET 2.0 adds support to hold the __VIEWSTATE in a few ways.
The abstract PageStatePersister class represents the base class that encapsulates the Page State storage and processing.
Storage can be done with the default HiddenFieldPageStatePersister class or with SessionPageStatePersister.
When SessionPageStatePersister is used, the .NET Server manages the _VIEWSTATE in a session object instead of a hidden field on your form.
Changing the state storage looks like this:

protected override PageStatePersister PageStatePersister
{
    get
    {
        return new SessionPageStatePersister(this);
    }
}


PageStatePersister can also be customized to use a Database, a File or any other storage device.
By extending this class, you can build your own solution

I hope you find this solution useful. Combined with a finely tuned SQLDataSource and along with ControlParameters, it can enrich your UI behavior and save your users time while editing data on your site.



About Us | Contact Us | Standards of Business Conduct | Employment
© InvertedSoftware.com All rights reserved