C# 在提交按钮的 OnClientClick 事件上调用 javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16979120/
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
calling javascript function on OnClientClick event of a Submit button
提问by Ravindra Kumar
In my asp.net page, I have three text boxes and one button.
First two text boxes are being used to get the value from the user and third one is being used to show the sum of first two boxes.
在我的 asp.net 页面中,我有三个文本框和一个按钮。
前两个文本框用于从用户处获取值,第三个文本框用于显示前两个框的总和。
I am calling a javascript function to sum the values and show the result value on OnClientClickevent of that BUTTON.
我正在调用一个 javascript 函数来对值求和并显示该OnClientClick按钮事件的结果值。
JS function is working fine but when I am pressing button to get the sum, it shows the result in third text box and just then the page is being post-back and result value becomes disappear from the third text box.
JS 函数工作正常,但是当我按下按钮获取总和时,它在第三个文本框中显示结果,然后页面正在回发,结果值从第三个文本框中消失。
Why the post-back is called by the button?
I don't want page to be post-backed on click of submit button.
为什么回发被按钮调用?
我不希望页面在点击提交按钮时被回传。
Any suggestion is appreciated.
任何建议表示赞赏。
采纳答案by sangram parmar
OnClientClick="SomeMethod()"event of that BUTTON, it return by default "true" so after that function it do postback
OnClientClick="SomeMethod()"该 BUTTON 的事件,它默认返回“ true”,因此在该函数之后它会回发
for solution use
溶液使用
//use this code in BUTTON ==> OnClientClick="return SomeMethod();"
//and your function like this
<script type="text/javascript">
function SomeMethod(){
// put your code here
return false;
}
</script>
回答by sangram parmar
<asp:Button ID="btnGet" runat="server" Text="Get" OnClick="btnGet_Click" OnClientClick="retun callMethod();" />
<script type="text/javascript">
function callMethod() {
//your logic should be here and make sure your logic code note returing function
return false;
}
</script>
回答by Pushpendra
The above solutions must work. However you can try this one:
上述解决方案必须有效。不过你可以试试这个:
OnClientClick="return SomeMethod();return false;"
and remove return statement from the method.
并从方法中删除 return 语句。

