William Rodswickerson
William Rodswickerson

Reputation: 33

Prevent adding new record whenever user clicks refresh

Hello there im having problem whenever i press the refresh button it keeps adding :/ how do i prevent it? its been my day 2 figuring this out and i failed :(

protected void Button1_Click(object sender, EventArgs e)
        {
            //Instantiate the connection with the database 
            using (SqlConnection myConnection = new SqlConnection("user id=username;" +
                                                                  "password=password;" +
                                                                  "trusted_connection=yes;" +
                                                                  "database=DataBaseConnection;" +
                                                                  "connection timeout=30;"))
            {
                //Open the Connection object
                myConnection.Open();

                //Instantiate a SQL Command with an INSERT query
                SqlCommand myCommand = new SqlCommand("INSERT INTO BasicInfo (Firstname,Surname) Values(@a,@b);", myConnection);

                if (TextBox1.Text !=null && TextBox2.Text != null)
                {
                    //Texbox 
                    myCommand.Parameters.AddWithValue("@a", TextBox1.Text);
                    myCommand.Parameters.AddWithValue("@b", TextBox2.Text);

                    //Execute the query
                    myCommand.ExecuteNonQuery();
                }
                else
                {
                    //Code HEre?
                }

Upvotes: 2

Views: 196

Answers (2)

rsbarro
rsbarro

Reputation: 27339

One way to handle this problem is to do a Response.Redirect at the end of the Button1_Click event back to original page. The Response.Redirect will make the browser do a GET request for the page, so if the user hits F5 they'll just redo the GET (and not POST the form again).

This approach is sometimes called the Post/Redirect/Get pattern. This blog post has a pretty good writeup of the approach: http://blog.andreloker.de/post/2008/06/Post-Redirect-Get.aspx

Upvotes: 4

ta.speot.is
ta.speot.is

Reputation: 27214

One strategy for preventing processing something multiple times is to assign a token to each form, as a hidden field.

Once you complete whatever processing is required in response to the form being submitted you revoke the token.

Alternatively, save the token as part of the processing and add a check to your processing to first see if that token has already been used.

This helps for any scenario where you might receive a request twice, for instance if a user double clicked on the button or a link.

Upvotes: 0

Related Questions