C# 如何使 ASP.NET 按钮调用客户端 javascript 而不是回发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13016660/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:21:37  来源:igfitidea点击:

How to make ASP.NET button call client side javascript and not do postback

c#javascriptasp.net.net

提问by Jim

I have a web app in ASP.NET with a C# code behind. The main login page is going to have a sort of touchpad type UI where there are buttons for 0-9 to enter a pin #.

我在 ASP.NET 中有一个 Web 应用程序,后面有一个 C# 代码。主登录页面将有一种触摸板类型的 UI,其中有 0-9 的按钮可以输入 pin #。

So, I'm new to ASP.NET and to JavaScript both. When these numeric buttons are clicked on the UI, nothing needs to be done on the server side - there shouldn't be any postback at all. All that needs be done is append a number to a label's text. I'm trying to figure out how to do that in JavaScript, without the button causing any kind of postback.

所以,我是 ASP.NET 和 JavaScript 的新手。当在 UI 上单击这些数字按钮时,服务器端无需执行任何操作 - 根本不应该有任何回发。所有需要做的就是在标签的文本中附加一个数字。我试图弄清楚如何在 JavaScript 中做到这一点,而按钮不会导致任何类型的回发。

To make the example much simpler, let's just say I have a UI with a single label and single button on the screen, and everytime you click this single button, it should append a 1 to the label's text. Here's my .aspx, but when I try to run this, I get a "Object Expected" exception at runtime...

为了使示例更简单,假设我有一个 UI,屏幕上只有一个标签和一个按钮,每次单击这个按钮时,它都应该在标签文本后附加一个 1。这是我的 .aspx,但是当我尝试运行它时,我在运行时收到“预期对象”异常...

EDIT: I've modified my example to include the suggestions made in answers below, and still am having issues. To reproduce, this .aspx code can be copied into the default.aspx of a new VS Web Application project, and run it and click the 1 button; it should append a 1 to the label's value, but it throws an "Object Expected" exception.

编辑:我已经修改了我的示例以包含在下面的答案中提出的建议,但仍然存在问题。要重现,可以将此.aspx 代码复制到新的VS Web 应用程序项目的default.aspx 中,并运行它并单击1 按钮;它应该将 1 附加到标签的值,但它会引发“预期对象”异常。

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestJavascript._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
  <form id="form1" runat="server">
    <div>
      <asp:Table ID="baseTable" runat="server" HorizontalAlign="Center">
        <asp:TableRow ID="labelRow" runat="server" HorizontalAlign="Center" Width="100" Height="30">
          <asp:TableCell ID="labelCell" runat="server" HorizontalAlign="Center" Width="100%" Height="100%" BorderStyle="Solid" BorderWidth="1px">
            <asp:Label ID="inputLbl" runat="server"/>
          </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow ID="buttonRow" runat="server" HorizontalAlign="Center">
          <asp:TableCell ID="buttonCell" runat="server" HorizontalAlign="Center">
            <asp:Button ID="btn1" runat="server" Text="1" Height="70px" Width="70px" OnClientClick="btn1Click()"/>
          </asp:TableCell>
        </asp:TableRow>
      </asp:Table>
    </div>
  </form>
  <script type="txt/javascript">
    void btn1Click()
    {
        document.getElementById('<%= inputLbl.ClientID %>').value += "1";
        return false;
    }
  </script>
</body>
</html>

Any help is much appreciated!

任何帮助深表感谢!

采纳答案by Francis P

First of all, a variable name should not start with a number, so replace 1Btnwith a significative name (btnAppendOne).

首先,变量名不应该以数字开头,所以1Btn用有意义的名字(btnAppendOne)代替。

  1. Bind the onclickclient event to your Button, in your PageLoadmethod:

    btnAppendOne.Attributes.Add("onclick", "return btnAppendOneClick();");
    
  2. Use the correct javascript (return falseshould cancel the postback):

    <script type="text/javascript">
         function btnAppendOneClick()
         {
             var updatedLabel = document.getElementById('<%=inputLbl.ClientID %>');
             updatedLabel.innerHTML = updatedLabel.innerHTML + "1";
             return false;
         }
    </script>
    
  1. onclick客户端事件绑定到您的Button, 在您的PageLoad方法中:

    btnAppendOne.Attributes.Add("onclick", "return btnAppendOneClick();");
    
  2. 使用正确的javascript(return false应该取消回发):

    <script type="text/javascript">
         function btnAppendOneClick()
         {
             var updatedLabel = document.getElementById('<%=inputLbl.ClientID %>');
             updatedLabel.innerHTML = updatedLabel.innerHTML + "1";
             return false;
         }
    </script>
    

回答by Josh Mein

You can use the OnClientClickattribute for the asp button and add return false;which prevents the postback:

您可以使用OnClientClickasp 按钮的属性并添加return false;防止回发的属性:

<asp:Button ID="1Btn" runat="server" Text="1" Height="70px" Width="70px" 
    OnClientClick="btn1Click(); return false;" />

回答by Adil

Use return false;statement, it will stop from postback; If you need postback then return true;from function.

使用return false;语句,它将停止回发;如果您需要回发,则return true;来自函数。

<script type="text/javascript">
void btn1Click()
{
    this.inputLbl.Text += "1";
    return false;
}
</script>

回答by Sam

there is a typo in your Script tag.. First Line (1)

您的 Script 标签中有一个错字。第一行 (1)

 <script type="**text**/javascript">
void btn1Click()
{
    document.getElementById('<%= inputLbl.ClientID %>').value += "1";
    return false;
}