Take a look at some of the more common uses of JavaScript in ASP.NET pages with some short examples.
Adding JavaScript to a Server Control
It is quite easy to add JavaScript to a specific server control that resides on an ASP.NET page. Let's take a look at the button server control as an example. If you drag and drop a Button HTML server control (
HtmlInputButton Class) onto a page and run it as a server control, it should have the following construction:<INPUT type="button" value="Button" runat="server" id="Button1">
This is a normal button that can be programmatically manipulated in the code-behind or server-side script of an ASP.NET page. For example, to assign the button text when the page is generated, simply use the value property of the button after this element is turned into an HTML server.
Visual Basic .NET
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Button1.Value = DateTime.Now.ToString()
End Sub
Visual C# .NET
void Page_Load(object sender, EventArgs e) {
Button1.Value = DateTime.Now.ToString();
}
This simply provides a button on the page that shows a date and time as the text of the button.
It is important to note that the ASP.NET page here gets the time from the server that generated the page. So if the Web server sits somewhere in the Central Time Zone of the United States (CST -6 GMT), then everyone who requests this page will get the same time no matter where they reside in the world.
What if you wanted the button to show the time of the person viewing the page? The easiest way of accomplishing this task would be to do this using JavaScript on the client-side.
For an example of this, we will place the end user's (the viewer of the web page) computer time on a button Web server control. The following code shows how to accomplish this task:
Visual Basic .NET
<%@ Page Language="VB" %>
<script runat="server">
Sub Button1_Click(sender As Object, e As EventArgs)
Response.Write("Postback!")
End Sub
</script>
<html>
<head>
</head>
<body onload="javascript:document.forms[0]['Button1'].value=Date();">
<form runat="server">
<p>
<asp:Button id="Button1" onclick="Button1_Click"
runat="server" Font-Bold="True" Font-Names="Verdana"
Font-Size="Larger"></asp:Button>
</p>
</form>
</body>
</html>
Visual C# .NET
<%@ Page Language="C#" %>
<script runat="server">
void Button1_Click(object sender, EventArgs e) {
Response.Write("Postback!");
}
</script>
<html>
<head>
</head>
<body onload="javascript:document.forms[0]['Button1'].value=Date();">
<form runat="server">
<p>
<asp:Button id="Button1" onclick="Button1_Click"
runat="server" Font-Bold="True" Font-Names="Verdana"
Font-Size="Larger"></asp:Button>
</p>
</form>
</body>
</html>
In this bit of code, notice how some of the button's attributes are assigned server side before being sent down to the client's browser. In this case, the font of the text on the button is changed to Verdana as well as to a bold font-type of a specific size. Once the button's HTML code is received on the client, the client-side JavaScript changes the text of the button to the current time on the end user's computer. The HTML code generated for the entire page will then appear as such:
<html>
<head></head>
<body onload="javascript:document.forms[0]['Button1'].value=Date();">
<form name="_ctl0" method="post" action="NewFile.aspx" id="_ctl0">
<input type="hidden" name="__VIEWSTATE"
value="dDwtNTMwNzcxMzI0Ozs+fGKi5Pun0h+xthnqTZtIR9yEzL4=" />
<p>
<input type="submit" name="Button1" value="" id="Button1"
style="font-family:Verdana;font-size:Larger;font-weight:bold;" />
</p>
</form>
</body>
</html>
Clicking on the button will still give you a postback (observed through the
Response.Write command) and a new time on the button control as the page is re-rendered.
In this case, we placed some JavaScript directly in the
<body> element of the page using the onload attribute. For the value of the onload attribute, we specifically pointed to the HTML element with the name Button1 that is in the first <form> section (as it is possible to have multiple forms in HTML).
This was an easy way to add some JavaScript to work with an ASP.NET Web server control. Though, we could have also just as easily added a JavaScript command to the button itself as shown here in the following partial code example:
Visual Basic .NET
<%@ Page Language="VB" %>
<script runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
Button1.Attributes.Add("onclick", _
"javascript:alert('ALERT ALERT!!!')")
End Sub
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<asp:Button id="Button1" runat="server" Font-Bold="True"
Font-Names="Verdana" Font-Size="Larger"
Text="Click Me!"></asp:Button>
</form>
</body>
</html>
Visual C# .NET
<%@ Page Language="C#" %>
<script runat="server">
void Page_Load(object sender, EventArgs e) {
Button1.Attributes.Add("onclick",
"javascript:alert('ALERT ALERT!!!')");
}
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<asp:Button id="Button1" runat="server" Font-Bold="True"
Font-Names="Verdana" Font-Size="Larger"
Text="Click Me!"></asp:Button>
</form>
</body>
</html>
Using a server control's attribute property is a great way to add additional JavaScript to a control that is control specific. In this case, the JavaScript was added using the Attribute.Add property along with the key of the script as well as the script itself (both represented as
string values).Performing a Simple Button-rollover
When it comes to buttons on a Web page, one of the more common functionalities that Web developers want to give their buttons is a rollover effect. The rollover effect experience is when the end user hover their mouse over a button on a Web page (without clicking the button) and the button itself changes color or shape. This can be especially useful for Web pages that have multiple buttons, and it would be beneficial from a usability standpoint to notify the end user of the button they would be clicking prior to clicking it.
This was fairly easy to do before server controls came along and it isn't that difficult now with server controls. The code for performing such an operation is as follows:
Visual Basic .NET
<%@ Page Language="VB" %>
<script runat="server">
Sub ImageButton1_Click(sender As Object, e As ImageClickEventArgs)
Label1.Text = "Postback!"
End Sub
</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>
Visual C# .NET
<%@ Page Language="C#" %>
<script runat="server">
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>
Instead of assigning the JavaScript to a server control through the
<body> element, this time we used the onmouseover and onmouseout events of the control. For each of these events, we assigned a JavaScript value. The onmouseover event is when the end user hover their mouse over the control and the onmouseout is for actions when the end user removes their mouse from hovering over the control. In our case, we want to show one image while the mouse hovers over the button and then show the original image from when the page was loaded when the mouse moves away from the button.
If you are working directly in the control such as this, instead of specifying the control in the
form as we did when working with JavaScript in the <body> element, you can use the this keyword followed by the property you are trying to change.Setting Control Focus
In the construction of Web Forms, notice that no property is enabled to set the focus of a Web server control (this will be an added feature in ASP.NET 2.0 Whidbey). Therefore when using the .NET Framework 1.0 or 1.1, you need to employ different methods to accomplish this task. You can do it just as you did before ASP.NET came along—using JavaScript.
For example, if your ASP.NET page has multiple text boxes on it, focus can be set to the first TextBox control when the page is loaded by employing the following code in the
<body> tag of the page.<body onload="document.forms[0]['TextBox1'].focus();">
Using this construct, when the page is loaded, the element that contains the ID
TextBox1 will employ the focus, and this enables the end user to start entering text directly without the need to use the mouse to position the focus.Changing the Control Focus Dynamically
To change the focus on the ASP.NET page dynamically, turn the
<body> tag into a HTML server control.<body id="Body1" runat="server">
Next, you can change the focus by placing the following code constructs in your ASP.NET server-side events.
Visual Basic .NET
Body1.Attributes("onload") = "document.forms[0]['TextBox2'].focus();"
Visual C# .NET
Body1.Attributes["onload"] = "document.forms[0]['TextBox2'].focus();";
Using this technique, you can assign the focus to other elements in the form. You might find this useful when using the OnTextChanged event if there are multiple elements in the form. If you don't do this, the end user must refocus on the form again using their mouse after an OnTextChanged event is fired due to the page postback.
Using Larger JavaScript Functions
Now that we can place pieces of JavaScript within HTML elements and even work with JavaScript and Web server controls in a dynamic fashion, how do you go about putting entire JavaScript functions in your code?
There are a couple of ways to accomplish this task and we will take a look at some of the more common methods that you can employ in your ASP.NET code
Keeping JavaScript in a Separate File (.js)
Keeping JavaScript functions in a separate file (a
.js file) is highly recommended. Once they are in a separate file and part of a project, the file can be imported into a page using some of the methods already described.
For instance, a
.js file can be included in an ASP.NET page using the following code:
<script type=”text/javascript” src=”a.js”></script>
You can put above code under head or body section.