How to Avoid Re-Submitting Data on Page Refresh?
In this article. I will explain 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.
There are following 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 Submit Button .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.
Hereunder is the C# Code behind:
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!");
}
}
}
Good, and thanks.