user1085240
user1085240

Reputation: 31

Handle page refresh in asp.net

private Boolean IsPageRefresh = false;
    protected void Page_Load(object sender, EventArgs e)
    {        
        if (!IsPostBack)
        {
            ViewState["postids"] = System.Guid.NewGuid().ToString();
            Session["postid"] = ViewState["postids"].ToString();
            TextBox1.Text = "Hi";
    }
    else
    {
        if (ViewState["postids"].ToString() != Session["postid"].ToString())
        {
            IsPageRefresh = true;
        }
        Session["postid"] = System.Guid.NewGuid().ToString();
        ViewState["postids"] = Session["postid"];
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
    if (!IsPageRefresh) // check that page is not refreshed by browser.
    {
        TextBox2.Text = TextBox1.Text + "@";

    }
}

i found this solution and its working for me.Buddy i could not understand that when page submitted then view state variable and session variable is same and after that i refresh page then view state and session variable have differt values while last time they have same value.

Upvotes: 2

Views: 4093

Answers (1)

Alexander Yezutov
Alexander Yezutov

Reputation: 3214

The idea is very simple.

Viewstate is basically some hidden input in the form. The idea is to detect page refresh after you submit the form once. This is to prevent taking an action twice.

So how it works.
First, when you create a form it has "1" (for example) both in Viewstate and in Session. After you submit it, "1" is retrieved from Viewstate and "1" is retrieved from session: you get IsPageRefreshed==false. At the same time "2" is written to Session and to the new Viewstate.

Let's say, now the user clicks "Back". In this case the HTML of the page is fetched from browser's cache and the Viewstate has a value of "1". If you submit the form now, it has then "1" in Viewstate and "2" in Session: IsPageRefresh==true

Upvotes: 2

Related Questions