Pages

Friday, August 13, 2010

Browser Refresh Issue with Ajax Modal Popup

Hello Programmers,
I got a strange issue when working with Ajax modal pop up extender control for the site.
At first glance everything seems perfect; However after playing with the website for some time I found this issue. In fact this issue could appear with any other normal asp.net button control.

The issue is Ajax modal pop up appears whenever we click browser “back” or “refresh” buttons or to  be exact the last fired event on the page re executes.

After doing some research in Google I came to know that it is the default browser behavior to trigger last fired page event whenever we hit browser refresh or back buttons.

Here is the optimal and easy solution:
We need to use of a date/time value set in a ViewState variable and a date/time stamp set in the Session variable.  When the page is first loaded, a Session variable is populated with the current date/time.  On the page's PreRender event, a ViewState variable is set to the value of the Session variable.  These two values are then compared to each other before the server side event code starts. 

If they are equal, then the execution is continues and the Session variable is updated with the current date/time, otherwise the command is skipped.

Step 1:
In the page load event, setup a session variable with current data & time value.

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
      {
            Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
}

Step 2:
In page PreRender event; set the ViewState value with the session value which we set in Step 1

protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
      ViewState["update"] = Session["update"];
}

Step 3: This would be crucial
Add a condition to check whether the session and ViewState timestamp values are equal.
If both values are equal the we continue execute the event and set new timestamp value into session variable else we can skip execution.

protected void btnAction_Click(object sender, EventArgs e)
{
if (Session["update"].ToString() == ViewState["update"].ToString())
      {
            //Some statements
            // ...
            //Some statements
            Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
}

You can try this at home and come to one conclusion ;-)