Home : Using ImageButton controls to execute JavaScript instead of posting back
Q10171 - HOWTO: Using ImageButton controls to execute JavaScript instead of posting back

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>

Related Articles
No Related Articles Available.

Article Attachments
No Attachments Available.

Related External Links
No Related Links Available.
Help us improve this article...
What did you think of this article?

poor 
1
2
3
4
5
6
7
8
9
10

 excellent
Tell us why you rated the content this way. (optional)
 
Approved Comments...
No user comments available for this article.

Powered By InstantKB.NET v1.3
Copyright © 2002, 2017. InstantASP Ltd. All Rights Reserved