CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

How to Prevent Duplicate Record Insertion on Refresh Click in Browser in ASP.Net ?
Submitted By Satheesh Babu B
On 7/6/2010 7:55:44 AM
Tags: ASP.Net,CodeDigest  

How to Prevent or Avoid Duplicate Record Insertion on Refresh(F5) Click in Browser in ASP.Net ?

 

One common problem we face when developing a Save or Submit input form will be insertion of duplicate data when clicking refresh(or F5) after clicking Submit or Save button. This is because clicking refresh will make the browser to re send the last request to the website. Thus, when clicking refresh after submitting a input form will insert a new duplicate record with the same data into your application database if it is not handled properly.

 

Moving forward, lets understand some of the common ways to prevent this duplicate record  insertion for refresh click in ASP.Net.
 
 
1) An easy way to prevent this is to put a Response.Redirect to the same page or to different page with a message saying "You have sucessfully posted your inputs".

 

Refer the code below,

protected void btnSave_Click(object sender, EventArgs e)
{
SaveEmployee(txtName.Text);
Response.Redirect(Request.Url.ToString());
}


public int SaveEmployee(string name)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        con.Open();
        SqlCommand com = new SqlCommand("Insert into employees (Empname) values('" + name + "')", con);
        int res = com.ExecuteNonQuery();
       con.Close();
        return res;
    }

 

The above code will redirect the user to the current page after saving the data using Response.Redirect. Since Response.Redirect will make a roundtrip to the client and load the page again with a fresh request, hitting refresh button will make the page to load again which is the last request.
 

2) Another way will be doing a check for duplicate data in your stored procedure before inserting any record. Use exists condition in SP like below,
 
If not exists( select Empname from employees where Empname = @name)
Begin
//insert the data
End
Else
Begin
// Do nothing
End


 
Happy Coding!!

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..