
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>hello world</title>
<script type="text/javascript">
function helloWorld(){
var firstAlert = "This is my first alert function called. I'm happy to learn Javascript.... happy programming";
alert(firstAlert);
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSample" runat="server" Text="Click Me" OnClientClick="helloWorld();" />
</div>
</form>
</body>
</html>
There are 2 types of controls in asp.net.
1. Server Side Controls - which is to call c# or vb functions and to perform server side operations like to call database, use dataTable, dataSet, etc
2. Client Side Controls - to perform client side operations
The above code uses asp.net Button which alerts a text in javascript. But if you note, after the alert, the request goes to the server because it is a server control. All server controls by default go to the server even if there is no event written for it. How to prevent this?
You can prevent an asp.net button hitting the server using javascript "return false" method. We have a property in asp.net button "OnClientClick" where we call the javascript method. We can return false in the method which it is calling so that there won't be any post back occured.
In the above example, "helloWorld" method alerts and finally returns false, which prevents to hit the server. You can also write this "return false" in the method property after calling the "helloWorld()" method as below:
<asp:button id="btnSample" runat="server" text="Click Me" onclientclick="helloWorld(); return false"></asp:button >
happy telling,
achu