aspnet網頁防止後退或重新整理造成重複提交

來源:互聯網
上載者:User

標籤:c#   webform   .net   asp   

aspnet網頁防止後退或重新整理造成重複提交


設網站有兩個網頁,提交第一頁後轉到第二頁,這時,如用通過瀏覽器的後退功能,會使瀏覽器再次呈現第一頁,這就可能出現重複提交,另外,轉到第二頁後,重新整理瀏覽器,也會退返回第一頁,也可造成重複提交。

理想的情況是這樣的,提交第一頁後轉到第二頁,這時,如用通過瀏覽器的後退功能,瀏覽器再次呈現第一頁,這時提交,則出現“網頁已到期”提示,並且不再執行提交轉跳等操作,或轉到第二頁後,重新整理瀏覽器,則出現“網頁已到期”提示。

現提供一種簡單的方法,範例程式碼如下:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="NoRepearSubmit.WebForm1" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title></head><body>    <form id="form1" runat="server">    <div>        <asp:Label ID="Label1" runat="server" Text="網頁已到期!"></asp:Label>        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />        <br />        <br />        </div>    </form></body></html>



using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace NoRepearSubmit{    public partial class WebForm1 : System.Web.UI.Page    {              protected void Page_Load(object sender, EventArgs e)        {            if (!IsPostBack)            {                Label1.Visible = false;                if (Session["IsForm1Valid"] == null)                {                    Session["IsForm1Valid"] = "true";                    ///下接初始化代碼                }                else                {                    if (Session["IsForm1Valid"].ToString() == "false")  Label1.Visible = true;//重新整理                }            }                    }        protected void Button1_Click(object sender, EventArgs e)        {            if (Session["IsForm1Valid"].ToString () == "true")            {                ///                ///正常的代碼位於此位置                ///                Session["IsForm1Valid"] = "false";                Server.Transfer("WebForm2.aspx");            }            else            {                Label1.Visible =true ;            }        }    }}
是不是很簡單,要點說一下,網頁提交時都會執行Page_Load方法,在上述代碼中所描述的網頁中,單擊按鈕後,首先會先執行Page_Load方法,然後才執行
Button1_Click方法,且此時的IsPostBack的值為真。第一次開啟網頁或重新整理瀏覽器時,也會執行Page_Load方式,且此時IsPostBack的值為假。

aspnet網頁防止後退或重新整理造成重複提交

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.