How To: Use OnClientClick() for your button controls
.NETSeptember 8, 2006
keithrull
I didn’t realize that this property exist up until today when i was playing with a custom control that i was building (don’t ask what control it is! ofcourse its a button). At first i don’t what to do with it since its something that was just injected in the .NET 2.0 framework but upon reading and understanding the method i realized that i could insert a javascript call inside this method call.. something similar to what i got used to doing which is adding attributes to the control at the page_init level.
Here’s the code listing of what i did:
The .aspx file
<%@ Page Language=“C#” AutoEventWireup=“true” CodeFile=“Default.aspx.cs” Inherits=“_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=“http://www.w3.org/1999/xhtml” >
<head runat=“server”>
<title>Keith’s OnClientClick Demo</title>
</head>
<body>
<form id=“form1” runat=“server”>
<div>
<asp:Button ID=“btnOne” runat=“server” OnClick=“btnOne_Click” Text=“Add Attribute” />
<asp:Button ID=“btnTwo” runat=“server” CausesValidation=“False” OnClick=“btnTwo_Click”
OnClientClick=“alert(‘Here you go! now you got an alert!’);” Text=“OnClientClick” /></div>
</form>
</body>
</html>
The code file:
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btnOne.Attributes.Add(“onclick”, “javascript:alert(‘test!’);”);
}
}
protected void btnOne_Click(object sender, EventArgs e)
{
Response.Redirect(“http://www.keithrull.com”);
}
protected void btnTwo_Click(object sender, EventArgs e)
{
Response.Redirect(“http://www.devpinoy.org”);
}
}
As you can see, we have accomplished the same results with what the Attributes.Add was able to accomplish by using the OnClientClick property.