Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent duplicate postback in ASP.Net (C#)

Simple one here... is there a clean way of preventing a user from double-clicking a button in a web form and thus causing duplicate events to fire?

If I had a comment form for example and the user types in "this is my comment" and clicks submit, the comment is shown below... however if they double-click, triple-click or just go nuts on the keyboard they can cause multiple versions to be posted.

Client-side I could quite easily disable the button onclick - but I prefer server-side solutions to things like this :)

Is there a postback timeout per viewstate that can be set for example?

Thanks

like image 754
isNaN1247 Avatar asked Aug 27 '10 10:08

isNaN1247


4 Answers

I dont think that you should be loading the server for trivial tasks like these. You could try some thing jquery UI blocking solution like this one. Microsoft Ajax toolkit should also have some control which does the same. I had used it a long time ago, cant seem to recall the control name though.

like image 75
Vinay B R Avatar answered Oct 04 '22 16:10

Vinay B R


With jQuery you can make use of the one event.

Another interesting read is this: Build Your ASP.NET Pages on a Richer Bedrock.

like image 41
Kris van der Mast Avatar answered Oct 01 '22 16:10

Kris van der Mast


Set a session variable when the user enters the page like Session["FormXYZSubmitted"]=false. When the form is submitted check that variable like

if((bool) Session["FormXYZSubmitted"] == false) {
   // save to db
   Session["FormXYZSubmitted"] = true;
}
like image 24
Zafer Avatar answered Oct 02 '22 16:10

Zafer


Client side can be tricky if you are using Asp.Net validation.

If you have a master page, put this in the master page:

 void IterateThroughControls(Control parent)
    {
        foreach (Control SelectedButton in parent.Controls)
        {
            if (SelectedButton is Button)
            {
                ((Button)SelectedButton).Attributes.Add("onclick", " this.disabled = true; " + Page.ClientScript.GetPostBackEventReference(((Button)SelectedButton), null) + ";");
            }

            if (SelectedButton.Controls.Count > 0)
            {
                IterateThroughControls(SelectedButton);
            }
        }
    }

Then add this to the master page Page_Load:

IterateThroughControls(this);
like image 42
JeffM Avatar answered Oct 04 '22 16:10

JeffM