Tải bản đầy đủ (.doc) (54 trang)

Tài liệu Tài liệu đào tạo ASP.NET pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (963.66 KB, 54 trang )

CÔNG TY CỔ PHẦN PHÁT TRIỂN ĐẦU TƯ CÔNG NGHỆ
FPT
Công ty Hệ thống thông tin FPT
TÀI LIỆU ĐÀO TẠO ASP.NET
Tài liệu đào tạo asp.net v1.0
Hà nội, 09/2009
Mục lục
I. Nền tảng lập trình web..........................................................................................1
Web Programming..................................................................................................2
II. ASP.NET...............................................................................................................3
III. Using JavaScript Along with ASP.NET.........................................................15
III.1 Adding JavaScript to a Server Control..........................................................15
III.2 Performing a Simple Button-rollover............................................................17
III.3 Setting Control Focus....................................................................................18
III.4 Changing the Control Focus Dynamically....................................................18
III.5 Using Larger JavaScript Functions...............................................................18
III.5.1 RegisterStartupScript Method........................................................................19
III.5.2 RegisterClientScriptBlock Method..................................................................20
III.5.3 The Difference Between RegisterStartupScript and RegisterClientScriptBlock
22
III.6 Keeping JavaScript in a Separate File (.js)....................................................22
IV. Data Access:.......................................................................................................23
SqlDataReader........................................................................................................23
SqlParameter...........................................................................................................24
Close Connection.....................................................................................................24
When good connections go bad................................................................................24
IIS 6 on Windows 2003 Server.................................................................................25
V. Microsoft Data Access Application Block........................................................27
V.1 Introduction:....................................................................................................27
V.2 Using Microsoft .net Data Access Application Block:..................................27
V.3 Accessing data without Data Access Application Block:..............................27


V.4 Retrieving Multiple Rows using SqlDataReader and Data Access
Application Block:........................................................................................................27
V.5 Retrieving Multiple Rows using DataSet:......................................................27
V.6 Retrieving a Single Row.................................................................................27
2/55
Tài liệu đào tạo asp.net v1.0
V.6.1 Stored Proc:....................................................................................................27
V.7 Explanation of the code:.................................................................................27
V.8 Retrieving XML Data:....................................................................................27
V.9
Explanation of the Code:...............................................................................................27
VI. Directory and File Access.................................................................................28
3/55
I. Nền tảng lập trình web
Tài liệu đào tạo asp.net v1.0
Web Programming
Modern Information Processing
2/55
Tài liệu đào tạo asp.net v1.0
Components of a Web Page
II. ASP.NET
ASP.NET Environment
• ASP.NET has a rich set of objects to work with in an object-oriented
and compiled programming environment
• The programming environment supports more than 25 .NET
languages, including built-in support for VB.NET, C#, and
JScript.NET
• .Net frame work
3/55
Tài liệu đào tạo asp.net v1.0

Page Structure
Server Controls and Script Processing
Form Submission
The <form> Control:
Web form controls are enclosed within a single <form> tag in the
format shown below:
<form runat="server">
...server controls and HTML code
</form>
Input Controls
Web Form Control Equivalent HTML Tag
<asp:Textbox/>
<input type="text">
<textarea>...</textarea>
<asp:RadioButton/>
<asp:RadioButtonList>
<input type="radio">
<asp:CheckBox/> <input type="checkbox">
4/55
Tài liệu đào tạo asp.net v1.0
<asp:CheckBoxList>
<asp:DropDownList/>
<asp:ListBox>
<select>...</select>
CheckBoxList:
public static string LoadCheckBoxList(CheckBoxList
pCtrl,string pCommandText,string pValueField,string
pTextField)
{
try

{
DataTable dt = new DataTable();
dt = GetDataTable(pCommandText);
pCtrl.DataSource = dt;
pCtrl.DataValueField = pValueField;
pCtrl.DataTextField = pTextField;
pCtrl.DataBind();
return "";
}
catch(Exception ex)
{
return ex.Message;
}
}
DropDownListControl:
public static string BindDropDownListControl(DropDownList
pCtrl,string pCommandText,string pValueField,string
pTextField,bool pRowBlank)
{
try
{
DataTable
dt=clsCommon.GetDataTable(pCommandText);
pCtrl.DataSource=dt;
pCtrl.DataTextField=pTextField;
pCtrl.DataValueField=pValueField;
pCtrl.DataBind();
pCtrl.Items.Insert(0,"");
dt=null;
5/55

Tài liệu đào tạo asp.net v1.0
return "";
}
catch(Exception ex)
{ return ex.Message; }
}
Output Controls
Web Form
Control
Equivalent HTML Tag
<asp:Label/> <span>...</span>
<asp:Panel> <div>...</div>
<asp:Table> <table>
<asp:Image/> <img>
Script Activation Controls
Scripts can be activated by user events surrounding the Web page. Certain controls,
then, are provided for trapping those events and taking action on them. The primary example
of a script activation control is the <asp:Button> control. The user clicks the button; a
subroutine is called in response.
Script activation controls come packaged with event handlers to trap and take action on user
events. The most common event is a mouse click on a button; the most common event
handler is the OnClick handler associated with the button. For example, the following button
definition,
<asp:Button Text="Submit" onClick="Display_Output" runat="server"/>
displays a button control with the label "Submit." It includes an OnClick event handler which
makes the button sensitive to a mouse click. When the button is clicked, the event handler
calls the Display_Output subprogram and that script is run.
There are a number of server controls designed for the purpose of trapping user events and
responding to them. The following controls are discussed in these tutorials:
Web Form Control Equivalent HTML Tag

<asp:Button/> <input type="button">
<asp:ImageButton/> <input type="image">
<asp:LinkButton/> <input type="button">
<asp:HyperLink/> <a href>
Script Activation Events
6/55
Tài liệu đào tạo asp.net v1.0
Scripts can be run in response to Web page events as well as to user events. A key
page event is the load event, which occurs when the page is first retrieved by the
server in response to a URL request. At the same time, there are two conditions under
which a page is loaded. On the one hand, it can be an initial page-load event -- the first
time the page is retrieved in response to a URL request; or, it can be a post-back
event -- a reloading of the same page on form submission. These two page-load events
can be, and often are, programmed separately.
<SCRIPT runat="server">
Sub Page_Load()
If Not Page.IsPostBack Then
--do this on initial page load
End If
--do this on every page load
End Sub
</SCRIPT>
In this example the Page_Load subroutine (this subprogram name is required) is run
every time the page is loaded. It is run when the page is initially accessed through a
URL request; it is run when the user clicks a control to call a subroutine. However, that
portion of the script enclosed within the If Not Page.IsPostBack condition is run only
the first time the page is loaded, not when responding to a user event to reload the
page, say when a button is clicked to submit a form. Many of the scripts in these
tutorials differentiate between initial page load and post-back load events.
Information Display Controls

There are three special controls that have no equivalence among standard form tags.
These controls are unique to ASP.NET and are designed to ease and to automate the
display of complex information. Most often these controls are used to display tables of
data from databases. They are designed so that minimal coding is required to extract
information from those tables and format it for display. We'll leave discussion of these
controls for later.
Web Form Control Equivalent HTML Tag
<asp:Repeater> (none)
<asp:DataGrid> (none)
<asp:DataList> (none)
The Page ViewState
This repopulation of controls with submitted values occurs through the page's View State. The
View State is the status of the page when it is submitted to the server. ASP.NET maintains this
status through a hidden field that it places on pages containing form controls. If you take a look
at the browser's source listing you will see this hidden field, named "__VIEWSTATE", and its
encoded value that looks something like the following:
<form name="_ctl0" method="post" action="page.aspx" id="_ctl0">
<input type="hidden" name="__VIEWSTATE"
value="dDwtMTI3OTMzNDM4NDs7PqIp6fnWsFyownq1sZyOLgKFOBwj" />
...
</form>
Maintaining Variables on PostBack
7/55
Tài liệu đào tạo asp.net v1.0
<SCRIPT runat="server">
Dim Counter As Integer
Sub Page_Load
If Not Page.IsPostBack Then
Counter = 1
CounterOut.Text = Counter

End If
End Sub
Sub Add_To_Counter (Src As Object, Args As EventArgs)
Counter += 1
CounterOut.Text = Counter
End Sub
</SCRIPT>
<asp:TextBox id="CounterOut" Columns="2" runat="server" />
<asp:Button Text="Add to Counter" OnClick="Add_To_Counter"
runat="server" />

Session Variables
There is a second method of retaining the values of variables between page postings. This
method also maintains values between different pages.
A user Session is created by ASP.NET whenever a visitor arrives at any Web page located in
your root application directory. A Session Object maintains identification information about the
visitor and allows ASP.NET to differentiate between visitors and their browsing status as they
navigate the Web site. Your visit to this tutorial site, for instance, is identified by the SessionID
value.
ArrayList/Datasource
An ArrayList can be bound to any of the list controls. In the following examples the previous
ColorList array is bound to CheckBoxList, DropDownList, and ListBox controls simply by
setting their DataSource properties and calling their DataBind() methods.
asp:CheckBoxList asp:DropDownList asp:ListBox
Red
Green
Blue
<asp:CheckBoxList id="CheckBoxes"
runat="server" />
CheckBoxes.DataSource = ColorList

CheckBoxes.DataBind()
<asp:DropDownList id="DropDownList"
runat="server" />
DropDownList.DataSource = ColorList
DropDownList.DataBind()
<asp:ListBox id="ListBox"
runat="server" />
ListBox.DataSource = ColorList
ListBox.DataBind()
Binding a DataSet to Controls
A DataSet, like a HashTable and SortedList, can provide the text labels and values that are
bound to list controls. In the following example, the four list controls are defined without their
asp:ListItem entries. This code is identical to that used to bind to previous list controls.
8/55
Tài liệu đào tạo asp.net v1.0
asp:RadioButtonList asp:CheckBoxList asp:DropDownList asp:ListBox
AltaVista
Excite
Google
Lycos
MSN
Yahoo
AltaVista
Excite
Google
Lycos
MSN
Yahoo
Go to Site Go to Site Go to Site Go to Site
Binding a Hashtable to Controls

A HashTable can be used to provide the text labels and values that are automatically
assigned to list controls: asp:RadioButtonList, asp:CheckBoxList, asp:DropDownList,
and asp:Listbox. In the following example, these four list controls are defined without their
asp:ListItem entries, and buttons are provided for scripting page transfers to the selected
URLs:
asp:RadioButtonList asp:CheckBoxList asp:DropDownList asp:ListBox
Lycos
MSN
Yahoo
AltaVista
Excite
Google
Lycos
MSN
Yahoo
AltaVista
Excite
Google
Go to Site Go to Site Go to Site Go to Site
Information Display Controls
Repeater Control
9/55
Tài liệu đào tạo asp.net v1.0
No. Name Price Qty. Amount
11111 Adobe Photoshop 345.95 10 3,459.50
22222 Adobe Illustrator 249.95 5 1,249.75
33333 Microsoft XP Upgrade 99.95 14 1,399.30
44444 Microsoft Office XP 699.99 9 6,299.91
55555 MacroMedia DreamWeaver 145.95 18 2,627.10
Total Value: $15,035.56

<asp:Repeater id="ProductsTable" runat="server">
<HeaderTemplate>
<table border="1" cellpadding="3" style="border-collapse:collapse">
<caption><b>Product List</b></caption>
<tr style="background-color:#F0F0F0">
<th>Picture</th>
<th>Item Information</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td rowspan="3">
<img src="<%# Container.DataItem("ItemNo") %>.jpg"/>
</td>
<td><%# Container.DataItem("ItemNo") %></td>
</tr>
<tr>
<td><%# Container.DataItem("ItemName") %></td>
</tr>
<tr>
<td><%# Container.DataItem("ItemPrice") %></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr style="background-color:#E0E0E0">
<td rowspan="3">
<img src="<%# Container.DataItem("ItemNo") %>.jpg"/>
</td>
<td><%# Container.DataItem("ItemNo") %></td>
</tr>

<tr style="background-color:#E0E0E0">
<td><%# Container.DataItem("ItemName") %></td>
</tr>
<tr style="background-color:#E0E0E0">
<td><%# Container.DataItem("ItemPrice") %></td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
<tr>
<td colspan="2" style="font-size:10pt">
<i>Source: Products.xml file</i>
</td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
Product List
10/55
Tài liệu đào tạo asp.net v1.0
Picture Item Information
11111
Adobe Photoshop
345.95
22222
Adobe Illustrator
249.95
33333
Microsoft XP Upgrade
99.95
44444

Microsoft Office XP
699.99
55555
MacroMedia DreamWeaver
145.95
Source: Products.xml file
DataList Control
<ItemTemplate>
<img src="<%# Container.DataItem("ItemNo")
%>.jpg" align="top"/>
<%# Container.DataItem("ItemNo") %><br/>
<%# Container.DataItem("ItemName") %><br/>
$<%# Container.DataItem("ItemPrice") %><br/>
</ItemTemplate>
<FooterTemplate>
Source: Products Database
</FooterTemplate>
11/55
Tài liệu đào tạo asp.net v1.0
Product List
11111
Adobe Photoshop
$345.95
22222
Adobe Illustrator
$249.95
33333
Microsoft XP Upgrade
$99.95
44444

Microsoft Office XP
$699.99
55555
MacroMedia DreamWeaver
$145.95
Source: Products Database
DataGrid Control
Product Name Product Price* Availability
Adobe Photoshop 345.95
In Stock
Adobe Illustrator 249.95
In Stock
Microsoft XP Upgrade 99.95
In Stock
Microsoft Office XP 699.99
In Stock
MacroMedia DreamWeaver 145.95
In Stock

*Average Street Price As of 09-23-2009
Displaying Calculated Values
Calculations for a Repeater Control
No. Name Price Qty.
11111 Adobe Photoshop 345.95 10
22222 Adobe Illustrator 249.95 5
33333 Microsoft XP Upgrade 99.95 14
44444 Microsoft Office XP 699.99 9
55555 MacroMedia DreamWeaver 145.95 18
<asp:Repeater id="ProductsTable" runat="server">
<HeaderTemplate>

<table border="1" cellpadding="3" style="border-collapse:collapse">
<tr style="background-color:#A0A0A0; color:#FFFFFF">
<th>No.</th>
12/55
Tài liệu đào tạo asp.net v1.0
<th>Name</th>
<th>Price</th>
<th>Qty.</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr style="text-align:right">
<td><%# Container.DataItem("ItemNo") %></td>
<td style="text-align:left"><%# Container.DataItem("ItemName")
%></td>
<td><%# Container.DataItem("ItemPrice") %></td>
<td><%# Container.DataItem("ItemQty") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
No. Name Price Qty. Amount
11111 Adobe Photoshop 345.95 10 3,459.50
22222 Adobe Illustrator 249.95 5 1,249.75
33333 Microsoft XP Upgrade 99.95 14 1,399.30
44444 Microsoft Office XP 699.99 9 6,299.91
55555 MacroMedia DreamWeaver 145.95 18 2,627.10
Summations for a Repeater Control

No. Name Price Qty. Amount
11111 Adobe Photoshop 345.95 10 3,459.50
22222 Adobe Illustrator 249.95 5 1,249.75
33333 Microsoft XP Upgrade 99.95 14 1,399.30
44444 Microsoft Office XP 699.99 9 6,299.91
55555 MacroMedia DreamWeaver 145.95 18 2,627.10
Total Value: $15,035.56
Control Reporting
No. Name Price Qty. Amount Order Status
11111 Adobe Photoshop 345.95 10 3,459.50
22222 Adobe Illustrator 249.95 5 1,249.75 On Order
33333 Microsoft XP Upgrade 99.95 14 1,399.30
44444 Microsoft Office XP 699.99 9 6,299.91 On Order
55555 MacroMedia DreamWeaver 145.95 18 2,627.10
13/55
Tài liệu đào tạo asp.net v1.0
Total Value: $15,035.56
Calculations for a DataGrid
No. Name Price Qty. Amount Order Status
11111 Adobe Photoshop 345.95 10 3,459.50
22222 Adobe Illustrator 249.95 5 1,249.75 On Order
33333 Microsoft XP Upgrade 99.95 14 1,399.30
44444 Microsoft Office XP 699.99 9 6,299.91 On Order
55555 MacroMedia DreamWeaver 145.95 18 2,627.10
Total: $30,071.12
Calculations for a DataList
No. 11111
Name Adobe Photoshop
Price 345.95
Qty. 10

Amount 3,459.50
Order Status
No. 22222
Name Adobe Illustrator
Price 249.95
Qty. 5
Amount 1,249.75
Order Status On Order
No. 33333
Name Microsoft XP Upgrade
Price 99.95
Qty. 14
Amount 1,399.30
Order Status
No. 44444
Name Microsoft Office XP
Price 699.99
Qty. 9
Amount 6,299.91
Order Status On Order
No. 55555
Name MacroMedia DreamWeaver
Price 145.95
Qty. 18
Amount 2,627.10
Order Status
Inventory Total: $45,106.68
14/55
Tài liệu đào tạo asp.net v1.0
III. Using JavaScript Along with ASP.NET

III.1 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 using either Microsoft
Visual Studio® .NET or the ASP.NET Web Matrix 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 control (right-click on the control and
select Run As Server Control).
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.
Figure 1. Showing the date and time on a 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 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">
15/55
Tài liệu đào tạo asp.net v1.0
<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. The result is shown in
Figure 2.
Figure 2. Clicking on the date button
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 C# .NET
16/55
Tài liệu đào tạo asp.net v1.0
<%@ 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).
III.2 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 hovers
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 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>
17/55

Tài liệu đào tạo asp.net v1.0
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 hovers 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.
III.3 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.
III.4 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 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.
III.5 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. For this article, we will look at the
RegisterStartupScript and the RegisterClientScriptBlock methods.
Note If you are a Visual Basic .NET developer using Visual Studio .NET 2002 or 2003, then
you will have to go into your options to turn on the ability to see these advanced methods. To do
this, when in Visual Studio .NET, in the menu bar, click on Tools > Options. Then in the Text
Editor folder, open the Basic folder. Within the Basic folder, uncheck the Hide advanced
members check box. This allows the methods we will be discussing in this article to be shown with
Microsoft Intellisense®. See Figure 3.
18/55

Tài liệu đào tạo asp.net v1.0
Figure 3. Showing advanced members in Visual Studio .NET
III.5.1 RegisterStartupScript Method
One of the first options available is to register script blocks using one of the .NET classes for this
purpose. The first is the RegisterStartupScript method. This class would be best used when you have
a JavaScript function that you want to initiate when the page is loaded. For an example of this, create
an ASP.NET page in Visual Studio .NET that contains two buttons.
Button1
and
Button2
should
be the IDs of the two buttons. Then place the following code within the Page_Load event.
Visual C# .NET
Page.RegisterStartupScript("MyScript",
"<script language=javascript>" +
"function AlertHello() { alert('Hello ASP.NET'); }</script>");
Button1.Attributes["onclick"] = "AlertHello()";
Button2.Attributes["onclick"] = "AlertHello()";
Using this code in the Page_Load event will produce the following HTML code in the browser (some
HTML code removed for clarity):
<HTML>
<HEAD>
<title>WebForm1</title>
</HEAD>
<body>
<form name="Form1" method="post" action="WebForm1.aspx"
id="Form1">
<P>
<input type="submit" name="Button1" value="Button"
id="Button1" onclick="AlertHello()" />

<input type="submit" name="Button2" value="Button"
id="Button2" onclick="AlertHello()" /></P>
<script language=javascript>function AlertHello() {
alert('Hello'); }</script>
</form>
</body>
</HTML>
Working with this ASP.NET page, notice that there is one JavaScript function that was placed at the
bottom of the page before the close of the form (
</form>
).
19/55
Tài liệu đào tạo asp.net v1.0
When working with the RegisterStartupScript method, the constructor asks for two parameters—the
first being the key of the script and the second being the script itself (represented as a
string
).
Page.RegisterStartupScript("MyScript", _
"<script language=javascript>" & _
"function AlertHello() { alert('Hello ASP.NET'); }</script>")
It is important that all the JavaScripts on the page have unique keys given to them. If there is more
than one JavaScript with the same key name, only the first one will be placed on the page.
III.5.2 RegisterClientScriptBlock Method
Now let's create a better version of the button rollover example by using the
RegisterClientScriptBlock method. The problem with the rollover button example from earlier is that
when the end user's mouse hovered over the button image, the rollover image had to be retrieved from
the server in a separate request. A better rollover button situation would be where the rollover image of
the button is already downloaded and stored in the browser's cache so that when the end user hovers
over the button, it is instantaneously displayed. To accomplish this we must build a JavaScript function.
The following example shows the JavaScript function as well as the use of the

RegisterClientScriptBlock method to get the function onto the page. For this example, the code-
behind only needs a Page_Load event and a button-click event for an ImageButton server control.
Visual C# .NET
<%@ 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"
20/55
Tài liệu đào tạo asp.net v1.0
ImageUrl="button1.jpg"></asp:ImageButton>
</p>
<p>
<asp:Label id="Label1" runat="server" />
</p>
</form>
</body>
</html>
Using this code, the HTML output to the browser will appear as follows:
<HTML>
<HEAD>
<title>WebForm1</title>
</HEAD>
<body>
<form name="Form1" method="post" action="WebForm1.aspx"
id="Form1">
<script language=javascript>if (document.images) {MyButton
= new

Image;MyButtonShaded = new Image;MyButton.src =
'button1.jpg';MyButtonShaded.src = 'button2.jpg';}else
{MyButton
= '';MyButtonShaded = '';}</script>
<P>
<input type="image" name="ImageButton1" id="ImageButton1"
onmouseover="this.src =
MyButtonShaded.src;window.status='Oh
Yes! Click here!';" onmouseout="this.src =
MyButton.src;window.status='';" src="button1.jpg"
border="0"
/></P>
<P>
<span id="Label1"></span></P>
</form>
</body>
</HTML>
With this output, notice that by using the RegisterClientScriptBlock, that the JavaScript function
appeared directly after the opening
<form>
element in the HTML code. In addition to adding a
JavaScript function using the RegisterClientScriptBlock method, we also added some additional
JavaScript (just for fun) so that text will appear in the browser's status bar when the end user hovers
over the mouse. This is shown in the Figure 4.
Figure 4. Rollover button in action
21/55
Tài liệu đào tạo asp.net v1.0
The nice thing with all this JavaScript is that the normal postback to server-side events works just fine.
Clicking on the ImageButton in this example causes a postback where the Label server control's text
property is changed.

III.5.3 The Difference Between RegisterStartupScript and
RegisterClientScriptBlock
So we have shown two different methods for placing JavaScript functions on an ASP.NET page—so what
is the difference? The main difference is that the RegisterStartupScript method places the JavaScript
at the bottom of the ASP.NET page right before the closing
</form>
element. The
RegisterClientScriptBlock method places the JavaScript directly after the opening
<form>
element
in the page. So what difference does this make? It can make quite a bit of difference as we will see.
For an example of this, here is a way to put focus on a text box on a page when the page is loaded into
the browser—with Visual Basic .NET using the RegisterStartupScript method:
Page.RegisterStartupScript("Testing", "<script
language=javascript>document.forms[0]
['TextBox1'].focus();</script>")
This works all well and fine because the textbox on the page is generated and placed on the page by the
time the browser gets down to the bottom of the page and gets to this little bit of JavaScript. But if
instead it was written like this (using the RegisterClientScriptBlock method):
Page.RegisterClientScriptBlock("Testing", "<script
language=javascript>document.forms[0]
['TextBox1'].focus();</script>")
Focus will not get to the textbox control and a JavaScript error will be generated on the page (shown in
the Figure 5).
Figure 5. Error executing JavaScript
The reason for this is that the browser will encounter the JavaScript before the text box is on the page.
Therefore, the JavaScript will not be able to find a
TextBox1
.
III.6 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:
Visual C# .NET
Page.RegisterClientScriptBlock("MyScript",
"<script language=javascript src='MyJavaScriptFile.js'>");
Once the
.js
file is imported into the ASP.NET page, any of the JavaScript functions can be called as
before. This is a great way to manage JavaScript functions and keep them separate from the other logic
22/55

×