Search code examples
asp.netpostbackautopostback

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


Here's my aspx page

<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>

And here's the code behind

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

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

When I click something in the dropdown, I get redirected to Page2, I then click the browser back button, and click the "Click Me!" btn. Instead of the btnClick even getting fired, it fires ddlChanged first, and does the redirect again.

Can this be solved without javascript?


Solution

  • You can use a session variable and store the last value in the dropdown, so when it fires you are like double-checking that effectively the dropdown.SelectedIndex change

    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");
    }