Sdílet prostřednictvím


How to: Respond to Button Web Server Control Events in Client Script

Button controls can raise both server events and client events. Server events occur after postbacks, and they are handled in the server-side code that you write for the page. Client events are handled in client script, typically JavaScript (ECMAScript), and they are raised before the page is submitted. By adding client-side events to ASP.NET button controls, you can perform tasks such as displaying confirmation dialog boxes before submitting the page, and canceling the page submission altogether.

To add client script, which handles the OnClientClick event, to a button Web server control

  • In the ASP.NET button Web server control to which you want to add client script (a Button, LinkButton, or ImageButton control), set the OnClientClick property to the client script that you want to run.

    Note

    If you want to be able to cancel the submission, set the OnClientClick property to the string "Return" and the function name. The client script can then cancel the submission by returning false.

    The following code example shows how to add a client-script click event to a Button control.

    <%@ Page Language="VB" %>
    <script runat="server">
        Sub Button1_Click(ByVal sender As Object, _
            ByVal e As System.EventArgs)
            Label1.Text = "Server click handler called."
        End Sub
    </script>
    
    <body>
      <form id="form1" runat="server">
        <asp:Button ID="Button1" Runat="server"
          OnClick="Button1_Click"
          OnClientClick="return confirm('Ready to submit.')"
          Text="Test Client Click" />
        <br />
        <asp:Label ID="Label1" Runat="server" text="" />
      </form>
    </body>
    </html>
    
    <%@ Page Language="C#" %>
    <script runat="server">
        void Button1_Click(Object sender, EventArgs e)
            Label1.Text = "Server click handler called.";
        End Sub
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <body>
      <form id="form1" runat="server">
        <asp:Button ID="Button1" Runat="server"
          OnClick="Button1_Click"
          OnClientClick="return confirm('Ready to submit.')"
          Text="Test Client Click" />
        <br />
        <asp:Label ID="Label1" Runat="server" text="" />
      </form>
    </body>
    </html>
    

See Also

Reference

Button Web Server Controls Overview