Tuesday, April 10, 2012

ASP:Button OnClientClick and OnClick not working

Sometimes you face really strange scenarios in Development, I faced a very strange issue about Event handlers while development of simple application. It proves that its not always Developers fault for coding defects.

I was creating a Search module in our application where I want call OnClientClick event for validation and if the validation returns true then perform search on DataSource using OnClick event of the Search button.

I have created a JavaScript function for validation and called that method in OnClientClick event
function ValidateSearch()
    var flag = true;
    // JavaScript code for validation
    return flag;
following is the ASP.Net code for Search button.
<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" OnClick="keywordSearch_Click" OnClientClick="ValidateSearch()" />

With above code it should call ValidateSearch() method first on click of Search button and based on the return value, it should call the Server-Side event.

Everything is OK, but above code didn't work, [Don't give up in such cases] 
I tried some other alternative like...

1) <asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" OnClick="keywordSearch_Click" OnClientClick="javascript:return ValidateSearch();" />

2) <asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" OnClick="keywordSearch_Click" OnClientClick="return ValidateSearch();" />

but still no Success.

We have to explicitly return the result after checking the functions return value. 

<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" OnClick="keywordSearch_Click" OnClientClick="if (!ValidateSearch()) { return false;};" />

Hope this helps you.


  1. Perfect solution. Scoured stackoverflow and couldnt find one that worked but this did! Reblogged

  2. Hey Hazelfresh, Only Developer can understand developer's need... I faced the same issue, hence added this solution in my blog. :)

  3. I had the same issue with an ImageButton, the client click worked and even when the Javascript function returned true the OnClick event in the code behind would trigger only if I set CausesValidation="false"

  4. Thanks...
    I faced the same issue...This blog helped me to find the solution.... :) Thanks...

  5. Awesome....Faced same issue and got help from here...Thanks

  6. Great! Thank you for posting this!

  7. It is great solution, thank you!. But I cannot get the idea what is wrong if I have more controls on the page with Onclick and OnClientClick event.
    No one of them works then.

  8. Hi, Thanks!! is there any reason why return Validate(); doesnt work?

  9. Thank you for sharing this