A common problem that Web Application developers encounter is 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 the WebForm's data into a database. This will result in the addition of duplicate rows in the database. But we have a constraint that we can't stop the user by refreshing the page. So, what to do? Although 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.
My strategy will make use of the ViewState feature. As we are using ViewState, it would seem logical to perform the operation in the LoadViewState and SaveViewState methods. Using these two methods, instead of the OnLoad method, has more benefits in that it eliminates the potential problems of sub-classes implementing Page_Load. methods follows:
public class Refresh : System.Web.UI.Page
{
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;
}
}
Thursday, February 4, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment