Technological Guide.

ASP.Net Page Refresh Problem

When the user refreshes a page in ASP.Net website, the recently taken place action will be repeated again such as calling a button click event / method like adding records to a database with the same values as inserted in the earlier state.

We can overcome this issue by making use of a variable in both Session State and View State collections to store the date and time of the events being called respectively Page Load and PreRender. When a page is first time loaded (!Page.IsPostBack) the date and time is being stored into a session variable as Session["update"] = System.DateTime.Now.ToString(). After the Page Load, before sending the page to the client, a PreRender event is called in which we will assign the Session["update"] value to ViewState["update"].

And when the user clicks the button, even the page load occurs also the Session["update"] will never change as its a postback call only and it directly executes the button code where exists a check to compare the value of Session["update"] to the value of ViewState["update"]. At this point of time the Session["update"] and ViewState["update"] will have the same value as PreRender occurs after the PageLoad. So the code inside the button click will be executed and Session["update"] will be updated with the System.DateTime.Now.ToString() again and always after Button_Click(), PreRender event of the Page will be executed in which ViewState["update"] value is updated with Session["update"].

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.

Leave a Reply