Keeping track of number of button clicks

2019-05-28 18:30发布

问题:

Let us assume that I have a page with a CAPTCHA image.

I want to let the user try to enter the code for three times, otherwise he is not allowed to do it anymore.

How can I keep track of the number of times the "Confirm" button has been clicked. The "Confirm" button has to perform a postback to the server every time it is clicked.

Using JavaScript is not good since if the user reloads the page, the counter would be set to zero. How can this be done please?

回答1:

This should be pretty straight forward. First set the counter to zero, and then update it on subsequent post backs:

if (!this.IsPostBack) { Session["RetryCount"] = 1; }
else
{
    int retryCount = (int)Session["RetryCount"];
    if (retryCount == 3) { // do something because it's bad }
    else { retryCount++; Session["RetryCount"] = retryCount; }
}


回答2:

Use ViewState to store the number.

Or better yet - Session.

The advantage of Session is that it is stored on the Server (AFAIK) so it can't be tampered with, and also that it will persist even when reloading the page.