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.
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...
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.
Solution:
We have to explicitly return the result after checking the functions return value.
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.
Perfect solution. Scoured stackoverflow and couldnt find one that worked but this did! Reblogged
ReplyDeleteHey Hazelfresh, Only Developer can understand developer's need... I faced the same issue, hence added this solution in my blog. :)
ReplyDeleteI 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"
ReplyDeleteThanks...
ReplyDeleteI faced the same issue...This blog helped me to find the solution.... :) Thanks...
Awesome....Faced same issue and got help from here...Thanks
ReplyDelete