Hossein Zahed

Web Developer, Entrepreneur, Software Educator

How to Avoid Re-Submitting Data on Page Refresh?

Here I will explain you how to prevent re-submitting data on browser page reload or refresh in your asp.net WebForm using C#. Sometimes we have some web pages through which we submit some user data to the database one after another on the same page. But the problem is, when we submit one user data and then refresh/reload our browser, what happens? The previously submitted data is re-submitted to the database. Here I am going to tell you how to prevent that.
 
Here below controls are taken in the WebForm:
1. TextBox TextBox1
2. Button SubmitBtn
 
And my work is when we type something in the TextBox1 and click on the SubmitBtn the page shows the given text of the TextBox1. And then if I refresh/reload the page it shows that the page is refreshed, not shows the text again. To do this I've used Session, ViewState and PreRender Event of the page.
Here is the C# Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            Session["Time"] = DateTime.Now.ToString();
    }
    protected void Page_PreRender(object sender, EventArgs e)
    {
        ViewState["Time"] = Session["Time"];
    }
    protected void SubmitBtn_Click(object sender, EventArgs e)
    {
        if (Session["Time"].ToString() == ViewState["Time"].ToString())
        {
            // Code for submitting data....
            Response.Write(TextBox1.Text + " Submitted!");
            TextBox1.Text = null;
            
            Session["Time"] = DateTime.Now.ToString();

        }
        else
        {
            // Code for page refresh....
            TextBox1.Text = null;
            Response.Write("Page Refreshed!");
        }
    }
}
Comments are closed