Saturday, September 22, 2012

Refresh Page Issue in ASP.Net


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 thePreRender 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) // If page loads for first time
    {
        // Assign the Session["update"] with unique value
        Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); 
        //=============== Page load code =========================




        //============== End of Page load code ===================
    }
}

protected void btnDisplay_Click(object sender, EventArgs e)
{ 
    // If page not Refreshed
    if (Session["update"].ToString() == ViewState["update"].ToString())
    {
        //=============== On click event code ========================= 

        lblDisplayAddedName.Text = txtName.Text;

        //=============== End of On click event code ==================

        // After the event/ method, again update the session 

        Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); 
    }
    else // If Page Refreshed
    {
        // Do nothing 
    }
}

protected override void OnPreRender(EventArgs e)
{
    ViewState["update"] = Session["update"];
}