65.9K
CodeProject is changing. Read more.
Home

Avoid inserting twice when user refresh page in ASP.NET

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (4 votes)

Aug 26, 2011

CPOL
viewsIcon

37794

Avoid inserting twice when user refresh page in ASP.NET

Hi all, This is something that I have done to avoid insertion of records into database twice when user presses refresh. It is so simple. I am just using session and view state, and comparing the dates stored in them. Here is the code:
'Storing the now date in session variable on page load:
Sub Page_Load (sender As Object, e As EventArgs)
    If Not Page.IsPostBack
        Session("update") = Server.URLEncode(System.DateTime.Now.ToString())
    End If
End Sub
'Storing the date also in view state on page prerender :\
Sub Page_PreRender (sender As Object, e As EventArgs)
    ViewState("update") = Session("update")
End Sub

Finally check if the dates are equal, so if yes we insert and update the session value to the date of insertion, thus the view state value and session value will not be equal in the next postback. Here is the code :

Sub Button1_Click(sender As Object, e As EventArgs)
    If Session("update").ToString() = ViewState("update").ToString() Then
        If AddEmployee(firstName.Text, lastName.Text) = 0
            Message.Text = "Success"
            Session("update") = Server.URLEncode(System.DateTime.Now.ToString())
        Else
            Message.Text = "Failure"
        End If
    Else
        Message.Text = "Failure - Session"
    End If
    firstName.Text = ""
    lastName.Text = ""
End Sub
Hope that you like it.