Introduction
In Web Programming, the refresh click or postback is the big problem which generally developers face. So in order to avoid the refresh page issues like, if user refreshes the page after executing any button click event/method, the same method gets executed again on refresh. But this should not happen, so here is the code to avoid such issues.
Using the Code
Here the page's PreRender
event and ViewState
variable helps to differentate between the Button click event call or the Refresh page event call. For example, We have a web page having button to display text entered in text box to the Label.
So when page is first time loaded, then a session["update"] object is assigned by some unique value, and then the PreRender
event is being called, where that session is assigned to the viewstate variable.
And on button click event, the session assigning code from page load will never called, as it is postback, so it directly calls the button click event where there is check whether the session and viewstate variables have same value. Here both values will be same. At the end of the click event method, the session variable is assigned with new unique value. Then always after click event, the PreRender
event gets called where that newly assigned session value is assigned to viewstate variable.
So whenever the page is being refreshed, viewstate value will become previous value (previous value is taken from viewstate hidden control) which will never match with current session value. So whenever the control goes in button click event, the match condition never gets satisfied hence code related to button click never gets executed.
Points of Interest
Here we can understand the page events flow as well as Viewstate
variable's workflow easily.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
}
protected void btnDisplay_Click(object sender, EventArgs e)
{
if (Session["update"].ToString() == ViewState["update"].ToString())
{
lblDisplayAddedName.Text = txtName.Text;
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
else
{
}
}
protected override void OnPreRender(EventArgs e)
{
ViewState["update"] = Session["update"];
}
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.