October 12, 2005

Detecting Page Refresh

How to stop the user from refreshing the page. The problem arises, if the previous request to the server was a PostBack, which, for example, inserts some data. This will result in the addition of duplicate rows in the database. we can’t stop the user from refreshing the page, but we can determine if this event has already occurred and then take appropriate action.

Create the function below and check Page.IsRefresh to check whether the page is resending the info. If you are using a base page from which all your pages are derived, then better you include this function on base page, so need not to duplicate the function. I m using Viewstate to store the info.

#region "Page Refresh Handling"

/// Code for checking the refresh event after any postback occured

private bool _refreshState;
private bool _isRefresh;

public bool IsRefresh
{
get
{
return _isRefresh;
}
}

protected override void LoadViewState(object savedState)
{
object[] allStates = (object[]) savedState;
base.LoadViewState(allStates[0]);
_refreshState = (bool) allStates[1];
_isRefresh = _refreshState == (bool) Session["__ISREFRESH"];
}

protected override object SaveViewState()
{
Session["__ISREFRESH"] = _refreshState;
object[] allStates = new object[2];
allStates[0] = base.SaveViewState();
allStates[1] = !_refreshState;
return allStates;
}

No comments:

Post a Comment