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?
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="" ).
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With