2011-12-12 61 views
2
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 + "@"; 

    } 
} 

,我發現這個解決方案及其me.Buddy工作我無法理解的是,當提交頁面然後查看狀態變量和會話變量是相同的,之後我刷新頁面然後查看狀態而會話變量在上一次具有相同的值時具有不同的值。處理頁面刷新

+0

您的問題是什麼? –

回答

2

這個想法很簡單。

Viewstate基本上是窗體中的一些隱藏輸入。這個想法是在您提交表單一次後檢測頁面刷新。這是爲了防止採取兩次行動。

所以它是如何工作的。
首先,當您創建表單時,它在Viewstate和Session中都有「1」(例如)。提交後,從Viewstate中檢索「1」,從會話中檢索「1」:您得到IsPageRefreshed==false。同時將「2」寫入Session和新的Viewstate。

比方說,現在用戶點擊「返回」。在這種情況下,頁面的HTML從瀏覽器的緩存中獲取,並且Viewstate的值爲「1」。如果您現在提交表單,則ViewState中的「1」和Session中的「2」:IsPageRefresh==true