How to Write Javascript in ASP.NET

One of the ways to employ Javascript in an ASP.NET application consists of adding HTML DOM events to standard control code.

The sample code below shows a default control:

<asp:Button id="Button1"
 runat="server"
 Text=”Button”></asp:Button>

Review the code with the addition of HTML DOM events:

<asp:ImageButton id="ImageButton1"
	onmouseover="this.src='button2.jpg'"
	onclick="ImageButton1_Click"
	onmouseout="this.src='button1.jpg'" runat="server"
	ImageUrl="button1.jpg"></asp:ImageButton>

Two methods exist for placing full Javascript functions in code. The first method, RegisterStartupScript, renders the script only after all elements load. Review sample code for the method below:

Page.RegisterStartupScript("MyScript",
	"<script language=javascript>" +
	"function AlertHello() { alert('Hello ASP.NET'); }</script>");
Button1.Attributes["onclick"] = "AlertHello()";
Button2.Attributes["onclick"] = "AlertHello()";

The second method, RegisterClientScriptBlock, functions best as a function definition called by RegisterStartupScript. Review sample code for the method below:

<%@ Page Language="C#" %>
<script runat="server">
	void Page_Load(object sender, EventArgs e) {
		Page.RegisterClientScriptBlock("MyScript",
			"<script language=javascript>" +
			"if (document.images) {" +
			"MyButton = new Image;" +
			"MyButtonShaded = new Image;" +
			"MyButton.src = 'button1.jpg';" +
			"MyButtonShaded.src = 'button2.jpg';" +
			"}" +
			"else {" +
			"MyButton = '';" +
			"MyButtonShaded = '';" +
			"}" +
			"</script>");
		ImageButton1.Attributes.Add("onmouseover",
			"this.src = MyButtonShaded.src;" +
			"window.status='Oh Yes! Click here!';");
ImageButton1.Attributes.Add("onmouseout",
			"this.src = MyButton.src;" +
			"window.status='';");
		}
		void ImageButton1_Click(object sender, ImageClickEventArgs e) {
			Label1.Text = "Postback!";
}
</script>
<html>
<head></head>
	<body>
		<form runat="server">
			<p>
				<asp:ImageButton id="ImageButton1"
				onmouseover="this.src='button2.jpg'"
				onclick="ImageButton1_Click"
				onmouseout="this.src='button1.jpg'" runat="server"
				ImageUrl="button1.jpg"></asp:ImageButton>
			</p>
			<p>
				<asp:Label id="Label1" runat="server" />
			</p>
		</form>
	</body>
</html>