ASP.NET/JavaScript - 为什么“返回假”不阻止回发?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3421329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET/JavaScript - Why Isn't "Return False" Not Preventing Postback?
提问by RPM1984
I feel like i've done this scenario plenty of times, and it usually works, so im obviously missing something.
我觉得我已经做了很多次这种情况,而且它通常有效,所以我显然错过了一些东西。
Here's my server-side ASP.NET Button:
这是我的服务器端 ASP.NET 按钮:
<asp:Button ID="btnFoo" runat="server" Text="Foo" CssClass="button foo" OnClientClick="foo_Click();" />
Which get's rendered on the client as:
哪个 get 在客户端呈现为:
<input type="submit" name="reallylongclientid" value="Foo" onclick="foo_Click();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(reallylongclientidandpostbackoptions, false, false))" id="reallylongclientid" class="button foo">
No surprises there.
那里没有惊喜。
Here's the surprise, in my JavaScript function:
这是我的 JavaScript 函数中的惊喜:
function foo_Click() {
return false;
}
Okay so there's more to it than that, but i cut it down to prove a point.
好吧,除此之外还有更多内容,但我将其删减以证明一点。
When i click the button, it calls the client-side function, and returns false.
当我单击按钮时,它调用客户端函数,并返回 false。
But it still posts back to the server, why?
但它仍然回发到服务器,为什么?
I basically want to do this on the click of the button:
我基本上想通过点击按钮来做到这一点:
- Do client-side validation.
- If validation passes, post back
- If not, show some error messages on the form.
- 进行客户端验证。
- 如果验证通过,回发
- 如果没有,请在表单上显示一些错误消息。
Of course, i could change this to an client-side button (input type="button") and manuallykick off the postback when i want, but i shouldn't need to do that. Or should i?
当然,我可以将其更改为客户端按钮(输入类型 =“按钮”)并在需要时手动启动回发,但我不需要这样做。还是我应该?
回答by Pranay Rana
write returnstatement so when you click on button it return falsewhich not allow to submit form
编写return声明,以便当您单击return false不允许提交表单的 按钮时
<asp:Button ID="btnFoo" runat="server" Text="Foo" CssClass="button foo"
OnClientClick="return foo_Click();" />

