谁能解释一下原因 btnSaveFile1 被点击, onClient点击 () 被调用,如果 onClient点击 () 返回 true 它调用服务器但是如果 onClientClick() 返回 false 它不调用服务器。我完全理解。
但为什么 不是这样? btnSaveFile2 似乎无论如何都不会调用服务器 onClientClick() 返回?
为什么 返回假; 必须内联吗?
<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:删除 UseSubmitBehavior="false"
更长的解释:
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.
如果您查看页面源代码,
onclick
渲染按钮不只是 "if(!onClientClick()){return false;}"
或 "return onClientClick();"
,因为它必须添加客户端脚本来发布表单。所以现在第一个按钮是:"if(!onClientClick()){return false;};__doPostBack('ctl00$MainContent$btnSaveFile1','')"
第二个是
"return onClientClick();__doPostBack('ctl00$MainContent$btnSaveFile2','')"
所以你可以看到情况#2,如果它返回
true
,它不会到达实际提交表单的脚本。 (按钮 1 不是这种情况,它确实到达了脚本并因此提交了表单)。
关于javascript - 何时调用服务器 onClick 与 OnClientClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20642419/