There are several ASP.NET ServerControls that can use JavaScript functions instead of server side code-behind that posts the whole page back. ASP.NET 2.0 ServerControls such as Button, ImageButton, and LinkButton, have a property called OnClientClick, where you can specify JavaScript to execute when it is clicked. In ASP.NET 1.1, you will have to add a client side onclick event programmatically, to achieve the same results.
Adding "return false;" to the executed JavaScript will stop the page from doing a full postback after the client code is executed.
ASP.NET 2.0
<!-- HTML/JavaScript -->
<asp:ImageButton ID="ImageButton1" runat="server" OnClientClick="RunClientCode(); return false;" />
<script language="javascript" type="text/javascript">
function RunClientCode(){
alert('Client code executed');
}
</script>
ASP.NET 1.1
// Code-behind
private void Page_Load(object sender, System.EventArgs e)
{
this.ImageButton1.Attributes["onclick"] = "RunClientCode(); return false;";
}
<!-- HTML/JavaScript -->
<asp:ImageButton ID="ImageButton1" runat="server" />
<script language="javascript" type="text/javascript">
function RunClientCode(){
alert('Client code executed');
}
</script>
Original Article:
Q10171 - HOWTO: Using ImageButton controls to execute JavaScript instead of posting back