星期二, 4月 27, 2010

[Asp.Net] 防止頁面重覆刷新執行的方法

#region check page refresh

    /// <summary>
    /// 處裡 PreRender 事件,在網頁初次載入時設置戳記,
    /// 且每次載入執行時會把該戳記存放到 HiddenField 裡。 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Page_PreRender(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.SetActionStamp();
        }

        if (Session["actionStamp"] != null)
            this.ClientScript.RegisterHiddenField("actionStamp", Session["actionStamp"].ToString());
    }

    /// <summary>
    /// 設置戳記
    /// </summary>
    private void SetActionStamp()
    {
        this.Session["actionStamp"] = Server.UrlEncode(DateTime.Now.ToString("yyyy-MM-dd.hh-mm-ss.FF"));
    }

    /// <summary>
    /// 取得值,指出網頁是否經由重新整理動作回傳 (PostBack)
    /// </summary>
    protected bool IsRefresh
    {
        get
        {
            if (HttpContext.Current.Request["actionStamp"] as string == 
                Session["actionStamp"] as string)
            {
                this.SetActionStamp();
                return false;
            }

            return true;
        }
    }

    #endregion

沒有留言:

張貼留言

留個話吧:)