如果单击浏览器后退按钮,则会触发不正确的偶数

时间:2015-07-10 17:47:09

标签: asp.net postback autopostback

这是我的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,然后我点击浏览器后退按钮,然后点击&#34;点击我!&#34; BTN。而不是btnClick甚至被解雇,它首先触发ddlChanged,并再次重定向。

这可以在没有javascript的情况下解决吗?

1 个答案:

答案 0 :(得分:1)

您可以使用会话变量并将最后一个值存储在下拉列表中,因此当它触发时,您就像是有效地重复检查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");
}