1

What I would like to do is be able to disable a button as soon as it pressed, perform an operation, and re-enable the button. Seemed simple enough, but my button doesn't update when I need it to. I tried an update panel, but I'm not sure if I'm using it correctly. Am I doing something wrong? Or is there a better way to achieve this?

HTML

<asp:UpdatePanel runat="server" ID="updateSubmitButton">
    <ContentTemplate>
        <a href="#resultsSet"><asp:Button ID="btnSearch" CssClass="CrossoverButton" runat="server" Text="Search" OnClick="btnSearch_Click" /></a>
    </ContentTemplate>
</asp:UpdatePanel>

C#

protected void btnSearch_Click(object sender, EventArgs e)
{
    btnSearch.Enabled = false;
    updateContent();

    // Do a lengthy operation here.

    btnSearch.Enabled = true;
}
Nate
  • 30,286
  • 23
  • 113
  • 184
Volearix
  • 1,573
  • 3
  • 23
  • 49

2 Answers2

6

You will need to use a client side technology to disable the button. This is because when you click the button, the page does a post back to itself, which tells the server to execute btnSearch_Click. Based on your code this will

  1. Disable the button
  2. Update the content
  3. Re-enable the button

all of this happens on the server. Only after the method has finished executing, does it return context to the page.

In order to disable the button on click, you'll want to try something this:

<asp:Button ID="btnSearch" CssClass="CrossoverButton" runat="server" Text="Search"
    OnClientClick="this.disabled = true;"
    UseSubmitBehavior="false" />
   OnClientClick="this.disabled = true;"

This line registers the client click handler, to disable itself.

   UseSubmitBehavior="false"

This line tells ASP.NET to include the disabled element in the form post, so the server knows which control registered the postback.

See also -- https://stackoverflow.com/a/11832053/86860

Community
  • 1
  • 1
Nate
  • 30,286
  • 23
  • 113
  • 184
0

All the actions in btnSearch_Click will be performed on server. The page will not be rendered until full page lifecycle ends.

If you want to disable the button you should use javascript to do this, and then only after disabling the button make a postback to the page.

dotnetom
  • 24,551
  • 9
  • 51
  • 54
  • pre_init code could be used as well but look into the page life cycle to see where you can implement your logic otherwise utilize the `__DoPostBack` method via java script – MethodMan Jun 04 '14 at 20:19
  • If you disable and enable button in server side you will not see it in the page, as you only get a response only after render step, which is at the end of page lifecycle – dotnetom Jun 04 '14 at 20:21
  • I think that placing the controls on an UPDatePanel would render a partial postback – MethodMan Jun 04 '14 at 20:37