简体   繁体   中英

when to call the Server onClick vs OnClientClick

Can someone please explain why btnSaveFile1 is clicked, onClientClick () is called and if onClientClick () returns true it calls the server but if onClientClick() returns false it doesn't call the server. Which I understand fully.

But why isn't that the case for btnSaveFile2 it seems to never call the server no matter what onClientClick() returns ?

Why does the return false; have to be inline ?

<asp:Button ID="btnSaveFile1" runat="server" Text="Save" OnClientClick="if(!onClientClick()){return false;}" OnClick="btnSaveFile_Click" UseSubmitBehavior="false" />


<asp:Button ID="btnSaveFile2" runat="server" Text="Save" OnClientClick="return onClientClick()" OnClick="btnSaveFile_Click" UseSubmitBehavior="false" />


 <script type="text/javascript">   
       function onClientClick() {
            if (CurrentMemberValidatedWindow()) {
                if (!ValidateForm()) {
                    return false;
                }
            }
            else {
                DeleteInvalidFiles();
                return false;
            }
            return true;
        }
 </script>

TL;DR: remove UseSubmitBehavior="false"

Longer explanation:

Use the UseSubmitBehavior property to specify whether a Button control uses the client browser's submit mechanism or the ASP.NET postback mechanism. By default the value of this property is true, causing the Button control to use the browser's submit mechanism. If you specify false, the ASP.NET page framework adds client-side script to the page to post the form to the server.

If you look at the page source, the onclick for the rendered button isn't simply "if(!onClientClick()){return false;}" or "return onClientClick();" , because it has to add client-side script to post the form. So now for the first button it is:

"if(!onClientClick()){return false;};__doPostBack('ctl00$MainContent$btnSaveFile1','')"

and for the second it is

"return onClientClick();__doPostBack('ctl00$MainContent$btnSaveFile2','')"

So you can see in case #2, if it returns true , it will not reach the script that actually submits the form. (this is not the case for button 1, which does reach the script and thus submits the form).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM