How to avoid duplicate entry of a record in database when user hits refresh.
Problem
In case we are saving data in database on click of a button, and what happens if a user hits refresh??
The data will be saved twice in the database. How can we avoid this behavior??
Solution
Solution to avoid duplicate entry of a record in database
Here is the solution in case the website is being developed in asp.net version 1.1 + with C# as the scripting language. The below implementation is designed by keeping “Order of page lifecycle events” in mind. The event order is Page_Load => btnSubmit_Click => Page_PreRender. The following code can be implemented to avoid the problem.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session[“RefrechCheck”] = DateTime.Now.ToString();
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
ViewState[“RefrechCheck”] = Session[“RefrechCheck”];
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid && Session[“RefrechCheck”].ToString() == ViewState[“RefrechCheck”].ToString())
{
Session[“RefrechCheck”] = DateTime.Now.ToString();
int result = SaveComment();
}
}
Happy coding.