cancel postback from javascript on confirm popup

2020-07-24 06:19发布

问题:

Following this problem ASP.NET: OnServerClick event handler not called if using onclick

I implemented a workaround:

<button id="idBtnPrint" runat="server" type="submit" onserverclick="BtnPrint_Click" onclick="confirmImpression();">print</button>

javascript function:

    function confirmImpression() {

        if (!confirm("sure ?"))
            arg.whatever;

    }

where confirmation is positive the postback is started when cancel the postback is not run (as I want) simply because an error generated js "arg is undefined" (normal because arg is not instanciate) script is locked and therefore no postback (as I want too).

but how to do this properly. I would not see the error appear in the status bar in the browser.

any suggestion is welcome!

thank you

回答1:

Simply wrap the confirmation in an if-block and return false if the confirmation fails. The standard javascript that generates the postback will be appended to the check and thus be run if the action is confirmed.

<button id="idBtnPrint" runat="server" type="submit"
        onserverclick="BtnPrint_Click"
        onclientclick="if (!confirm('sure ?')) { return false; }">print</button>

The reason that arg is undefined is that you don't use it as an argument nor is it defined in the window object. I assume that you're trying to hook into the validation system, but it won't work in this case because the validation logic isn't being invoked. You simply want to stop execution of the client-side handler if the user answers in the negative and the above code will do that.

Though the answer in the referenced question will work as well I prefer to use a full javascript statement to aid in understanding what is going on.



回答2:

I ran into a problem very similar to this, and even though this question is old, I thought my answer might help someone down the road. When you have a javascript method that is supposed to return something and you place it in the OnClientClick, it still doesn't return what the method really returns. In order to fix this issue, you have to return the method in the OnClientClick.

OnClientClick="return MethodName()"

You also need to make sure that your method is returning the correct true/false from the confirmation dialog.

function MethodName() {
    if (!confirm('Are you sure you want to X?')){
         return false;
    }
    else{
         return true;
    }
}


回答3:

You want to use OnClientClick and just return the opposite of what the confirm returns...

<button ... onclientclick="return !confirm('Are you sure ?');">print</button>