Wednesday, August 29, 2012

Asp.Net Button OnClientClick Example


The Asp.Net button has 2 attributes to trigger a click event OnClick and OnClientClick.

OnClientClick
– Calls the client side (JavaScript) event handler
OnClick – Calls the server side (code-behind) event handler

The
OnClientClick event handler will be executed first, followed by the OnClick event handler.

Here is a full example

.aspx page


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>OnClientClick</title>
    <script language="javascript">
        function JavascriptFunction() {
alert("Hi! I am a Javascript Function");
        }
    </script>
</head>
<body>
    <form id="frmOnClientClick" runat="server">
    <div>
        <asp:Button
            id="btnSave"
            runat="server"
            Text="Client Click"
            OnClientClick="JavascriptFunction();"             
            onclick="btnSave_Click"/>
    </div>
    </form>
</body>
</html>

.aspx.cs page (code-behind)

protected
void btnSave_Click(object sender, EventArgs e)
{
  Response.Write("Hi! I am a Server side (code-behind) Function");
}

Here when the user clicks on the button the client side Javascript function JavascriptFunction() will be called first and an alert message Hi! I am a Javascript Function will popup, once the user clicks ok in the message box the server side function btnSave_Click will be executed and the message Hi! I am a Server side (code-behind) Function will be displayed on the screen.

Search Flipkart Products:
Flipkart.com

No comments: