September 24, 2012

Button onClick and onClientClick

This is a simple example to show the difference between OnClick and OnClientClick event of asp:Button.
HTML Code

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
        function ConfirmThis() {            
            if (confirm('Do you want to server-side click?')) {
                return true;
            }
            else {
                return false;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtResult" runat="server" />
        <asp:Button ID="btnClick" runat="server" Text="Click Here" OnClick="btnClick_Click" 
            OnClientClick="return ConfirmThis();" />
    </div>
    </form>
</body>
</html>

Code-Behind

protected void btnClick_Click(object sender, EventArgs e) 
        {
            txtResult.Text = "Server side clicked";
        }

Now run your project. just Click on the button “Click Here”. It will ask to “Do you want a server-side click?”. If you select YES then you will do a server trip and when you select NO you will not redirect to server. So here for validation purpose we are using onClientClick and for doing process on server side, we are using onClick.