Freigeben über


Disabling an (posted by Aaron)

I consistently see people looking for easy ways to disable asp:buttons after they're clicked. The most common problem is that a user will click a button 20+ times not knowing that their action has been sent to the server. As you know, this can create a big problem really click. There are ways to avoid this on the server obviously, but easiest and most friendly solution would be just to disable the button after it's clicked.

Well, if you've ever tried, you realize that what seems like an easy task - isn't. If you add any code to the button to force it to a disabled state after being clicked the postback event never fires. Argh.

Well, here's an easy way to accomplish the exact same thing but instead of using an asp:button you simply using an input button with runat="server". Works like a charm.

<input type="button" id="btnNext" runat="server" value="Next" onserverclick="btnNext_Click" onclick="this.disabled=true;">

Aaron

Comments

  • Anonymous
    October 06, 2005
    Usually, I do use a slightly enhanced ClickOnceButton class from CodeProject: http://www.codeproject.com/aspnet/ClickOnce_Button_Control.asp
  • Anonymous
    October 06, 2005
    Great little tip, multiple clicking can really muck up a webapp that doesn't take this problem into consideration.
  • Anonymous
    October 06, 2005
    Aaron,

    I don't think this will work if you have client side validators on your page. If the validators display an error message on the first button click, the button will get disabled and you will never be able to post the form.

    -raj
  • Anonymous
    October 06, 2005
    I do the following to disable the asp:button.

    Client side:

    <script language="javascript">
    function disablebuttonTask()
    {
    window.setTimeout('disableAfterTimeout()',0);
    }
    function disableAfterTimeout()
    {
    document.mainForm.btnContinue.disabled = true;
    }
    </script>

    server side:
    private void Page_Load(object sender, System.EventArgs e)
    {
    if(! IsPostBack)
    {
    btnContinue.Attributes.Add("onclick", "disablebuttonTask();return true");
    }
    }

    private void btnContinue_Click(object sender, System.EventArgs e)
    {
    DateTime dt = new DateTime();
    dt = DateTime.Now.AddMilliseconds(10);
    while(System.DateTime.Now < dt)
    {}
    }


    Hope this helps :)
    - Rachit
    (rachitpatel at y a h o o . c o m)
  • Anonymous
    October 07, 2005
    Yeah, there are definitely limitations (like using validators and such). But if you're looking for a quick way to disable a button w/o writing a lot of code, this works really well.

    Rachit, great little example. I'm definitely going to look into your solution more. Good stuff.