views:

42

answers:

2

I have some code like below in an aspx page:

...
    function CheckEditing() {
            var answer = confirm('You are currently editing an item.  If you continue to the next page your changes will not be saved.  Would you like to continue?');
            if(!answer)
            {
                return false;
            }
            return true;
    }
.....
<asp:Button ID="btn_Next" runat="server" Text="Next" onclick="btn_Next_Click" OnClientClick="CheckEditing();" />

I had thought that returning false would keep my asp.net OnClick even from firing, but it still does. I've confirmed that it is getting to the return false section of code using alerts. Is there anything I can do to stop it from firing using jQuery/javascript?

+2  A: 

Change your OnClientClick like this:

OnClientClick="if(!CheckEditing()) return false;"

Because it renders as if(!CheckEditing()) return false; ASPNetFunction() you wouldn't want to return outright, or the second function would never run.

Nick Craver
Isn't that the same thing that i'm doing now?
Abe Miessler
@Abe - Nope, you're calling it, but not doing a `return false` overall...currently your `return false` in the function isn't being used for anything outside the function, like cancelling the `onclick` handler :)
Nick Craver
To add to Nicks response. You could keep you JS function the same and just put `OnClientClick="return CheckEditing();"`
Dustin Laine
Worked! You both rock!
Abe Miessler
@Dustin - You can't *always*, for the reasons I laid out above :) There's a function *after* this one that needs to be called.
Nick Craver
@Nick, hmm it worked for me. Does it make a difference that one is on the client click event?
Abe Miessler
@Abe - Depending on the .net version, it'll fix this for you, I posted the always safe route :)
Nick Craver
I think I see what I was missing, if he added an explicit return true at the end. That should work, correct?
Dustin Laine
@Dustin - Correct as well, it's always returning ~false at the moment :)
Nick Craver
The __doPostBack() call in onclick should only appear if you've set UseSubmitBehavior to false.
Dave Ward
Alright I added a `return true;` to the end. Thanks for the help.
Abe Miessler
A: 

You can achieve this also, in this way.

Declare a custom validator with the appropriate client validation function

Now, as a part of your button, set the validation group to be the same as the custom validator

Inside the function CheckEditing(), set args.IsValid = false for not going onto the onClick event

Function CheckEditing(source,args) { //... args.IsValid = false; }

Kushal Vaghani