Matthew
Matthew

Reputation: 4607

Page Refresh and Counter Value

I have a web page which, on page load, initializes a counter to 0. On every postback, the counter, which is saved in a session, is incremented by 1 until it reaches a value of 4. Basically, the idea behind this is that the user is given 4 chances to enter a username and the CAPTCHA image displayed on screen. If the user fails for 4 times (thus the use of the counter), he is redirected to an error page.

This is the code in my page load:

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        Label_Error.Visible = false;
        Session["Count"] = 0;
    }

    else
    {
        if (Session["Count"] == null)
        {
            Session.Abandon();
                Response.Redirect("CheckOutErrorPage.htm");
        }

        else
        {
            int count = (int)Session["Count"];
            count++;
            Session["Count"] = count;
        }
    }
}

The check for count == 4 is being done when the button is clicked. Now the code works fine. If the user clicks on the button for 4 times, he is not allowed anymore. The only problem crops up if the user hits the refresh button. As a matter of fact, once the user hits refresh, the counter is set to 0 and he has another 4 attempts. How can I stop this from happening? I don't want the counter to be set to 0 on page refresh. I want the counter's value to remain as it is. How can I do this please?

Upvotes: 1

Views: 3236

Answers (1)

Adrian Wragg
Adrian Wragg

Reputation: 7401

The problem fundamentally is this segment:

if (!this.IsPostBack)
{
    Label_Error.Visible = false;
    Session["Count"] = 0;
}

If you were to check whether the session variable existed first, rather than overwriting the value automatically, that may solve your problem:

if (!this.IsPostBack)
{
    Label_Error.Visible = false;
    Session["Count"] = Session["Count"] ?? 0;
}

Of course, that does assume that the user doesn't clear out their cookies and start a new session.

Upvotes: 6

Related Questions