How to avoid duplicate entry from asp.net on Postback

asp.netpostbackrefresh

I have a dropdown list that pulls data from template table. I have an Add button to insert new template. Add button will brings up jQuery popup to insert new values. There will be a save button to save the new data. On_Save_Click I enter the new data and close the popup.

Here is the proplem:
When I refresh the page, the page entering the values again. So, I get duplicate entries!

Question:
How can I avoid this issue? I check out Satckoverflow and Google, both they suggest to redirect to another page. I don't want to redirect the user to another page. How can I use the same form to avoid this issue? Please help.

Best Answer

You can use viewstate or session to indicate if data already inserted (button pressed).

Something like this:

private void OnbuttonAdd_click()
{
   if(ViewState["DataInserted"] != "1")
   {
      ...
      // Add new entry...
      ...
      if(data inserted successfully)
      {
         ViewState["DataInserted"] = "1";
      }
   }
}

Edit:

public bool DataInserted
{
    get
    {
        if (HttpContext.Current.Session["DataInserted"] == null)
        {
            HttpContext.Current.Session["DataInserted"] = false;
        }
        bool? dataInserted = HttpContext.Current.Session["DataInserted"] as bool?;

        return dataInserted.Value;
    }
    set
    {
        HttpContext.Current.Session["DataInserted"] = value;
    }
}

...

private void OnbuttonAdd_click()
{
   if(!DataInserted)
   {
      ...
      // Add new entry...
      ...
      if(data inserted successfully)
      {
         DataInserted = true;
      }
   }
}
Related Topic