如果单击浏览器后退按钮,甚至会触发错误

An incorrect even gets triggered if the browser back button is clicked

这是我的 aspx 页面

<asp:Label runat="server" ID="lbl" Text="suff goes here" /><br />
<asp:Button runat="server" OnClick="btnClick" ID="btn" Text="Click me!" />
<asp:DropDownList runat="server" ID="ddl" 
                  OnSelectedIndexChanged="ddlChanged" 
                  AutoPostBack="true">
    <Items>
        <asp:ListItem>a</asp:ListItem>
        <asp:ListItem>b</asp:ListItem>
        <asp:ListItem>c</asp:ListItem>
    </Items>
</asp:DropDownList>

这是背后的代码

protected void btnClick(object sender, EventArgs e)
{
    lbl.Text = DateTime.Now.Ticks.ToString();
}

protected void ddlChanged(object sender, EventArgs e)
{
    Response.Redirect("Page2.aspx");
}

当我在下拉列表中单击某些内容时,我被重定向到 Page2,然后我单击浏览器后退按钮,然后单击 "Click Me!" btn。它甚至没有触发 btnClick,而是先触发 ddlChanged,然后再次进行重定向。

不用javascript能解决这个问题吗?

您可以使用会话变量并将最后一个值存储在下拉列表中,因此当它触发时您就像仔细检查dropdown.SelectedIndex 是否有效更改

protected void ddlChanged(object sender, EventArgs e)
{
    // If the var is NULL then it is the first time the event gets triggered
    if (Session["lastDropDownValue"] != null)
        //If it has a value, and also is the same selected index, then it really doesn't change
        if (Convert.ToInt32(Session["lastDropDownValue"].ToString()) == ddl.SelectedIndex)    
            return; 

    //Set your variable for future validations 
    Session["lastDropDownValue"] = ddl.SelectedIndex;
    Response.Redirect("Page2.aspx");
}