When using a standard asp:Button component, it is necessary to use the following technique to cancel an automatic postback (or make a postback conditionally):
-
Specify the client-side operations via the Button.OnClientClick property;
-
Implement a logic that returns a Boolean value that indicates whether or not a postback should performed.
The following does not cancel a postback (despite of the “OnClientClickHandler” method returns “false”):
<asp:Button ID="btn" runat="server" OnClientClick="OnClientClickHandler();" />
function OnClientClickHandler() {
return false;
}
The following implementation does:
<asp:Button ID="btn" runat="server" OnClientClick="return OnClientClickHandler();" />
It looks like that this behavior is caused by specifics of the JavaScript code scope. Anyway, I am interested in the low-level implementation details of this scenario.
Why doesn’t the first implementation (where there is no “return” operator before the “OnClientClickHandler” method call) work?
The reason why you need to add
returnis because returning false from an event handler is the way to cancel the default behavior (in this case, submit the form).Another way to do the same is executing
event.prefentDefault()OnClientClick="OnClientClickHandler();"would be equivalent towhile
OnClientClick="return OnClientClickHandler();"would be equivalent toDo you see the difference? In the first case you’re just executing the function, but returning nothing.