Wednesday, August 29, 2012

Asp.Net Button OnClientClick prevent post back.


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.

In some cases we will have to stop calling the server side event after executing the client side event (Ex: When the client side validation fails), this can be achieved by returning false from the client side function which handles the OnClientClick
event as follows.

Here is a full example



<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>OnClientClick</title>
    <script language="javascript">
        function JavascriptFunction() {
            // Add validation code here.
            // If validation fails
            // return false to stop server side event.
            return false;
        }
    </script>
</head>
<body>
    <form id="frmOnClientClick" runat="server">
    <div>
        <asp:Button
            id="btnSave"
            runat="server"
            Text="Client Click"
            OnClientClick="if(!JavascriptFunction()) return false;"
            onclick="btnSave_Click"/>
    </div>
    </form>
</body>
</html>


Search Flipkart Products:
Flipkart.com

No comments: