Tài liệu Tài liệu đào tạo ASP.NET - Pdf 91

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

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

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

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

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

<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>

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

<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

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

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();">

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

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

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()" />

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!";
}

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.

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


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status