Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Page Refresh Causes Duplicate POST in ASP.NET Applications

Tags:

asp.net

i have an application in which i am adding a new record and the record is added two times if i am pressing refresh button.

I am clearing the cache but i am having the same problem. what to do?

like image 838
Annie Avatar asked Apr 13 '09 10:04

Annie


People also ask

Is page refresh a postback?

A refresh mean a complete reload of the page, without any form data. This is essentially an HTTP GET . A post back is when the page is posted to itself (through the form action="" ).

How can we prevent duplicate entries in database in asp net?

I recommend you use . FirstOrDefaultAsync instead of SingleOrDefaultAsync, specially if the database already has data and there is the possibility that a duplicate already exists. In this scenario, SingleOrDefaultAsync would throw and error but FirstOrDefaultAsync works as intended.


2 Answers

Once you have handled a post back to a page, best practice is to then redirect so that you can't have the data posted a second time using the "refresh" button. This is common to all web develoment, not just ASP.NET.

like image 171
David M Avatar answered Oct 07 '22 23:10

David M


My method is shamelessly stolen from page 4 of this awesome article on ASP Alliance. To detect a refresh, you can store the same value in ViewState and Session. If the user refreshes a page, it will PostBack using the old ViewState data that does not match your Session value. Once you detect this, you can create a Page that all of your other Pages inherit from with a simple variable to test for whether the user refreshed the browser. This solution requires ViewState to be enabled and a valid Session.

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    if (IsPostBack && ViewState[REFRESH_CHECK_GUID] != Session[REFRESH_CHECK_GUID])
    {
        IsRefresh = true;
    }
    Session[REFRESH_CHECK_GUID] = System.Guid.NewGuid().ToString();
    ViewState[REFRESH_CHECK_GUID] = Session[REFRESH_CHECK_GUID];
}

/// <summary>
/// True if the last PostBack was caused by a Page refresh.
/// </summary>
public virtual bool IsRefresh
{
    get;
    private set;
}
like image 41
Chris Shouts Avatar answered Oct 07 '22 21:10

Chris Shouts