How to prevent duplicate record insertion on Page refresh

ASP.Net developers frequently face this problem, duplicate records will be inserted when user refreshes or reload the page. This is because of When a web form is submitted to a server through an HTTP POST request, a web user that attempts to refresh the server response in certain user agents can cause the contents of the original HTTP POST request to be resubmitted, possibly causing undesired results, such as a duplicate web purchase. To avoid this problem, many web developers use the PRG(Post/Redirect/Get) pattern. – From Wiki. There is two solutions for the problem.

First solution – Redirect users to the same page or any other page, with a query string which may help to show the status of the insert operation.Like this code

if (IsDataSaved())
{
    Response.Redirect(Request.Url.AbsolutePath + "?status=1", false);
}

And in the page load we can verify the query string and shows message to the user.

Second solution This solution is using Session and View state objects. If View State is not enabled, it can be possible using Hidden Field also.

Here is the implementation

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Session["Update"] = Server.UrlEncode(DateTime.Now.ToString());
    }
}

protected override void OnPreRender(EventArgs e)
{
    ViewState["Update"] = Session["Update"];
    base.OnPreRender(e);
}

protected void cmdSave_Click(object sender, EventArgs e)
{
    if (Session["Update"].Equals(ViewState["Update"]))
    {
        SaveData();
        Session["Update"] = Server.UrlEncode(DateTime.Now.ToString());
    }
}

In page load, if the page is not in postback, we are assigning DateTime.Now to Session object and in the pre render event, assigning the same value to a view state object. And in the button click, we are verifying whether both view state and session values are same. If both the values are same, continue the Database insert operation and update the session value. If no, user refreshed the page.

Happy Programming :)

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>