Avoid Duplicate record insertion on page refresh in ASP.NET
One
of most common issue which many of the web developers face in their web
applications, is that the duplicate records are inserted to the
Database on page refresh. If the web page contains some text box and a
button to submit the textbox data to the database. In that case when the
user insert some data to the textbox and click on the submit button, it
will save the record to the Database and then if the user refresh the
web page immediately then the same record is again saved to the database
as there is no unique keys that can be used to verify the existence of
the data, so as to prevent the multiple insertion.
From this behavior we can definitely know that, on the page fresh the button click event is fired.
|
To avoid this problem we can try this method as discuss below.
On
page load event save the date/time stamp in a session variable, when
the page is first loaded, a Session variable is populated with the
current date/time as follows:
|
void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
Session["update"] =
Server.UrlEncode(System.DateTime.Now.ToString());
}
}
On the page's PreRender event, a ViewState variable is set to the value of the Session variable as follows:
void Page_PreRender(object obj,EventArgs e)
{
ViewState["update"] = Session["update"];
}
Then these two values are compared to each other immediately before the database INSERT command is run.
If
they are equal, then the command is permitted to execute and the
Session variable is updated with the current date/time, otherwise the
command is bypassed as given below:
void btnSubmit_Click(object obj, EventArgs e)
{
string name = "";
string qualification = "";
if (Session["update"].ToString() == ViewState["update"].ToString())
{
if (txtName.Text != "" || txtName.Text != null)
{
name = txtName.Text.ToString();
}
if (txtQualification.Text != "" || txtQualification.Text != null)
{
qualification = txtQualification.Text.ToString();
}
//--- Insert data function should be execute here
string
strSql = "INSERT INTO Testdata (Name,Qualification) VALUES ('" + name +
"','" + qualification + "')";
SqlConnection ANConnection = new SqlConnection(ConnectionString);
ANConnection.Open();
SqlCommand ANCommand = new SqlCommand(strSql, ANConnection);
ANCommand.ExecuteNonQuery();
ANConnection.Close();
ANConnection.Dispose();
//--End of save data
lblMessage.Text = "Inserted Record Sucessfully
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
else
{
lblMessage.Text = "Failure – Due to Page Refresh";
txtName.Text = "";
txtQualification.Text = "";
}
}
Note:
that ViewState needs to be enabled on the page for this to work; if
ViewState is not enabled then a hidden form field may be used instead.
Awesome, I've been trying different techniques without luck since I stay on the same page on submit. Good article, thank you!
ReplyDelete