How to avoid duplicate entry of a record in database when user hits refresh.

database

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.more

SAVE YOUR TIME AND MONEY

Save your time and money by choosing us, a scalable team with 120+ professionals with expertise in various domains and technologies.

Dedicated TL / PM with Quick Response

Have a dedicated Team Lead / Project Manager for your each project, all with an assurance that your project will get utmost priority, along with the quick and firm response for all your queries regarding it.

QUICK, SECURE AND SWIFT CODE

With expertise on all the latest architectural and coding structures, our experienced developers ensure that the site is secure, and performs quick and swiftly.

Leave us your info

Select Service

Describe your requirement here

Upload An Attachment