database

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

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.

Recent News Post
Advantages of ASP.NET Development
Sep10

Advantages of ASP.NET Development

ASP.Net is a powerful framework used for the development of dynamic web pages, website and web based applications....
View More
Benefits of Outsourcing Software Development to India
Jan20

Benefits of Outsourcing Software Development to India

The most successful business strategy adopted by organizations worldwide today is certainly outsourcing their software development requirements to...
View More