Sunday, January 12, 2014

Handling page refresh (F5) in ASP.NET post backs

Handling page refresh (F5) on post backs is one of the biggest problem for many web applications.Usually we used the simplest solution by redirecting to the same page after the action, but not always usefull.
In the previous post we saw how to handle a multiple user clicks on the same button.
but still user can overdo things by page refresh (F5). 
I use a header user control in all my applications which I found is the best place to handle this. The theory is F5 will post a older viewstate so if we have anything to compare we can skip the action from being perfomed once again.
The below code in .NET2.0 goes well with IE.
Insert it in your page or some common header/banner control 
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Session["PostID"] = "1001";
        ViewState["PostID"] = Session["PostID"].ToString();
    }
}
public bool IsValidPost()
{
    if (ViewState["PostID"].ToString() 
        == Session["PostID"].ToString())
    {
        Session["PostID"] = 
        (Convert.ToInt16(Session["PostID"]) + 1).ToString();
        ViewState["PostID"] = Session["PostID"].ToString();
        return true;
    }
    else
    {
        ViewState["PostID"] =
         Session["PostID"].ToString();
        return false;
    }
}
Now in your button click verify if the postback is real button click
public void ActionEvent(object sender, CommandEventArgs e)
{
 if (IsValidPost())
 {
  DoPocessing();
 }
}

0 comments:

Post a Comment