RoyT
RoyT

Reputation: 139

SQL insert statement executed twice

what is the best way to prevent user double click or refresh page that would cause execute SQL insert statement twice, I've tried to disable the button after click, but the result is not really good. I am expecting that it is possible to do it from code-behind. something more like SQL commit and rollback

Upvotes: 1

Views: 949

Answers (2)

Alex Norcliffe
Alex Norcliffe

Reputation: 2489

If you wish to protect against this you're going to need the server to be aware that the current user has already begun an action, and can't begin it again until a condition is met.

You need to be able to identify that user amongst the many that are potentially visiting your site. This is most simply done using SessionState, but if you have no other need for SessionState and wish to scale your application massively, a simple random cookie to identify the user can be used as a prefix for any keys that you use to place items into the server cache.

Let's say you used SessionState. You'd do something like the following (pseudo):

public void StartAction()
{
  var inProgress = HttpContext.Current.Session["actionInProgress"] as bool;
  if (!inProgress)
  {
     try
     {
        HttpContext.Current.Session["actionInProgress"] = true;
        MySqlController.DoWork();
     }
     finally
     {
        HttpContext.Current.Session["actionInProgress"] = false;
     }
  }
}

The above does not account for the following:

  • Catching exceptions and/or closing any connections in your finally block
  • Queueing up subsequent actions as a result of the next clicks on your client (this pseudo-code just returns if the action is already in progress)
  • I've gone for the simplest solution, but in reality a better practise would be to have this encompassed as a service which runs asynchronously so that you can monitor the progress both for the benefit of the user, and for the prevention of multiple parallel processes.

Upvotes: 1

dani herrera
dani herrera

Reputation: 51655

Perhaps PRG wikipedia article can help to you:

Post/Redirect/Get (PRG) is a common design pattern for web developers to help avoid certain duplicate form submissions and allow user agents to behave more intuitively with bookmarks and the refresh button.

Upvotes: 1

Related Questions