views:

596

answers:

3

hello,

I have an asp.net image button and I want to cancel the click event incase he fails the client side validation... how do I do that?

A: 

There is an OnClientClick event you can set this to your javascript function. If you return true it will continue to the post back. If you return false the post back will not happen.

<asp:Button ID="NavigateAway" runat="server" OnClientClick="javascript:return PromptToNavigateOff();" OnClick="NavigateAwayButton_Click" Text="Go Away" />

  <script type="text/javascript">
    function PromptToNavigateOff()
    {
        return confirm("Are you sure you want to continue  and loose all your changes?");
    }

  </script>
Aaron Fischer
A: 

I would simply reverse logic and not allow the user to click the button until he has filled the information. Put mandatory markers and if it is filled it then the button is enabled.

Bug
+1  A: 
<asp:ImageButton OnClientClick="return ValidatorOnSubmit()" />

The ValidatorOnSubmit() function should already be included by the ASP.NET framework if you have validators on your form. The standard WebForm onsubmit function looks like this:

function WebForm_OnSubmit() {
   if (   typeof(ValidatorOnSubmit) == "function" 
       && ValidatorOnSubmit() == false) return false;

   return true;
}
Mark Cidade