Thursday, July 10, 2014

Avoid Resubmitting Events On Web Page Refresh

Resubmitting events during a web page refresh can be detrimental. For example, you don't want your code to make another add to the database or resubmit a credit card charge. You could redirect your user to a confirmation page when a submit button is pressed. A page refresh will only affect the confirmation page. That may not fit your scenario.

Using ASP.NET ViewState

I ran across a nice piece of code at and repeated below that detects a page refresh using the ViewState.

Add this in your class:
#region Browser Refresh

private bool refreshState;
private bool isRefresh;

protected override void LoadViewState(object savedState)
  object[] AllStates = (object[])savedState;
   refreshState = bool.Parse(AllStates[1].ToString());
   if (Session["ISREFRESH"] != null && Session["ISREFRESH"] != "")
   isRefresh = (refreshState == (bool)Session["ISREFRESH"]);

protected override object SaveViewState()
   Session["ISREFRESH"] = refreshState;
   object[] AllStates = new object[3];
   AllStates[0] = base.SaveViewState();
   AllStates[1] = !(refreshState);
   return AllStates;


And in your button click do this:

protected void Button1_Click(object sender, EventArgs e)
   if (isRefresh == false)
     Insert Code here

Using AJAX

You can also avoid the event re-submission by using AJAX to handle your button events.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.