javascript - ASP.NET - onclick attribute added to Button means page cannot determine source of postback - Stack Overflow

admin2025-04-21  1

I've just added some JavaScript to the onclick of a Button in ASP.NET to disable the button (in order to prevent the user submitting the form twice).

When I click this button, the page posts back fine but no control event handler runs - ASP.NET seems unable to determine which control posted the page back.

I'm a bit stumped by this unexpected behaviour. Can anyone explain it and suggest an alternative way of doing this?

I've just added some JavaScript to the onclick of a Button in ASP.NET to disable the button (in order to prevent the user submitting the form twice).

When I click this button, the page posts back fine but no control event handler runs - ASP.NET seems unable to determine which control posted the page back.

I'm a bit stumped by this unexpected behaviour. Can anyone explain it and suggest an alternative way of doing this?

Share Improve this question asked Jan 25, 2011 at 19:47 DavidDavid 16.1k23 gold badges95 silver badges154 bronze badges 2
  • Is it an ASP.NET Button control or an HTML button? If it's an ASP.NET Button control, is the JavaScript in OnClick or OnClientClick? – knight0323 Commented Jan 25, 2011 at 20:03
  • It's an ASP.NET Button server control. I've added onlick="Foo();" directly to the markup by extending the control (i.e. through inheritance). – David Commented Jan 25, 2011 at 22:15
Add a ment  | 

2 Answers 2

Reset to default 3

If you disable the button before it posts back, the server side event is not registered.

The easier way to handle this is to hide the button after click, or create a handler that keeps the second click from cascading to the form post.

Last time I had this problem using .style.display = "none" in the onclientclick did the trick I needed. Disabled is not just a style, its a state, that the server respects.

<asp:Button ID="Button1" OnClientClick="javascript:this.style.display = 'none'" 
 onclick="Button1_Click" runat="server" Text="Button" />

Try This:

<asp:Button ID="Button1" UseSubmitBehavior="false" 
     OnClientClick="javascript:document.getElementById('Button1').disabled = true;    __doPostBack('__Page', '');" 
     onclick="Button1_Click" runat="server" Text="Button" />

It'll e through with no extra request inspection needed.

After your ment about how you add the onclick: Just add _doPostBack('_Page', 'YOURBUTTONNAME') and inspect the event args on the server side.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745216065a290856.html

最新回复(0)