Avoid Inserting Duplicate Record on Page Refresh

While working with asp.net forms, a common problem one faces is the resubmission of data everytime the page is refreshed.  What happens here is, once the submit button is clicked, the data is saved in the viewstate and everytime when the page is refreshed, the data from the viewstate is submitted to the server. So, even validation fails. Some of the ways to tackle this problem include

Allow unique rows to be added/validate from database

 A simple solution would be to check in the database for the presence of such duplicate records. However it is not much practical and not recommended.

Check TimeStamp across each postback

One solution is proposed by this article http://www.dotnetspider.com/resources/42823-How-Avoid-Re-Submitting-Data-Page-Refresh.aspx.
It stores the current time in Session in each postback and compares it with viewstate during the page pre_render event.. And the resubmission is checked by comparing the time saved at these two states.
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            Session["Time"] = DateTime.Now.ToString();
    }
    protected void Page_PreRender(object sender, EventArgs e)
    {
        ViewState["Time"] = Session["Time"];
    }
    protected void SubmitBtn_Click(object sender, EventArgs e)
    {
        if (Session["Time"].ToString() == ViewState["Time"].ToString())
        {
            // Code for submitting data....
            Response.Write(TextBox1.Text + " Submitted!");
            TextBox1.Text = null;
            
            Session["Time"] = DateTime.Now.ToString();

        }
        else
        {
            // Code for page refresh....
            TextBox1.Text = null;
            Response.Write("Page Refreshed!");
        }
    }

Using a update panel

Apparantly, using update panel seems to solve the problem, however using update panels for such simpler tasks would lead to their overuse which is considered potentially dangerous and an overkill.

Clearing the Header

A better and easier approach would be to use Response.Redirect  back to the same page after the insert command. This will prevent the post headers from transmitting.  Using Request.Url.ToString() as the first parameter of Response.Redirect will cause both the URL and the page's querystring to be included in the redirect.  The use of false as the second parameter will suppress the automatic Response.End that may otherwise generate a ThreadAbortedException.  A disadvantage of this approach is that any ViewState that had been built up will be lost.
 
//insert into database
Response.Redirect(Request.RawUrl,false);
Facebook Facebook LinkedIn LinkedIn

Leave a Comment

For Gravatar icon