You are on page 1of 105

TP BI GING

LP TRNH NG DNG WEB

GV: Nguyn Th Thanh Thun


Nguyn B Phc

TP HCM, thng 5/2010


1

MC LC

Chng 1: Gii thiu ASP.NET .................................................................................................... 5


1.1. Gii thiu....................................................................................................................................... 5
1.2. Xy dng ng dng web n gin ............................................................................................. 5
1.2.1. To ng dng web ................................................................................................................ 5
1.2.1.1. Thit k giao din .............................................................................................................. 7
1.2.1.2. M ngun x l .................................................................................................................. 8
1.2.2. Lu li trang web .................................................................................................................. 8
1.2.3. Bin dch v chy ng dng web ........................................................................................ 9
1.2.4. M ng dng Web .............................................................................................................. 10
1.2.5. Thm trang web mi ........................................................................................................... 11
1.3. IsPostBack ................................................................................................................................... 12
Chng 2: Web Control................................................................................................................ 13
2.1. Gii thiu..................................................................................................................................... 13
2.2. HTML Server Control ............................................................................................................... 13
2.3. ASP.NET Web Co ntrol ............................................................................................................. 13
2.4. ASP.NET List Control............................................................................................................... 16
2.6. ASP.NET Validation Control ................................................................................................... 20
2.6.1. RequiredFieldValidator ...................................................................................................... 20
2.6.2. RangeValidator.................................................................................................................... 20
2.6.3. CompareValidator ............................................................................................................... 20
2.6.4. RegularExpressionValidator.............................................................................................. 21
2.6.5. CustomValidator ................................................................................................................. 21
2.6.6. ValidationSummary ............................................................................................................ 21
Chng 3: Master Page, CSS, User Control ............................................................................. 22
3.1. Master Page v Style Sheet ....................................................................................................... 22
3.1.2 To trang Master page ......................................................................................................... 22
3.1.2.1 To th mc cho trang Master Page ............................................................................... 22
3.1.2.3 Thit k trang layout ........................................................................................................ 23
3.1.3. Cascading Style Sheets (CSS) ........................................................................................... 24
3.1.3.1. Dng Style cho Master Page .......................................................................................... 24
3.1.3.2. Dng Style cho ContentPlaceHolder............................................................................. 25
3.1.4. S dng trang Master Page ................................................................................................ 25
2

3.2. Web User Control....................................................................................................................... 27


3.2.1 To mt Web User Control................................................................................................. 27
3.2.2 S dng Web User Control ................................................................................................. 28
Chng 4: Cc i tng trong ASP.NET ................................................................................ 29
4.1. ViewState .................................................................................................................................... 29
4.2. Response...................................................................................................................................... 29
4.3. Request ........................................................................................................................................ 29
4.4. Application .................................................................................................................................. 30
4.5. Session ......................................................................................................................................... 30
4.6. Cookies ........................................................................................................................................ 31
4.7. Server ........................................................................................................................................... 32
4.8. Exception..................................................................................................................................... 34
Chng 5: Kt ni d liu vi ADO.NET .................................................................................. 36
5.1. Gii thiu..................................................................................................................................... 36
5.2. Cc i tng trong ADO.NET ............................................................................................... 36
5.2.1. Connection ........................................................................................................................... 36
5.2.2. Command ............................................................................................................................. 36
5.2.2.1 Thuc tnh .......................................................................................................................... 36
5.2.2.2 Phng thc ....................................................................................................................... 37
5.2.3. DataReader........................................................................................................................... 37
5.2.4. DataAdapter ......................................................................................................................... 38
5.2.5. DataSet ................................................................................................................................. 38
5.2.6. DataTable ............................................................................................................................. 38
5.2.7. DataView ............................................................................................................................. 38
5.3. Kt ni d liu trong ASP.NET ............................................................................................... 38
5.3.1. Thm ..................................................................................................................................... 38
5.3.2. Xo ........................................................................................................................................ 39
5.3.3. Hiu chnh ............................................................................................................................ 40
Chng 6: iu khin lin kt d liu ........................................................................................ 43
6.1. Gii thiu..................................................................................................................................... 43
6.2. GridView ..................................................................................................................................... 43
6.3. DataList ....................................................................................................................................... 45
6.3.1. Cc thnh phn ca DataList ............................................................................................. 46
6.3.2. To iu khin DataList ..................................................................................................... 46
6.3.3. To ngun d liu cho DataList dng AccessDataSource ............................................ 47
6.3.4. Thit k giao din cho cc thnh phn trong DataList ................................................... 48
3

6.3.5. Lin kt d liu cho cc thnh phn trong DataList ....................................................... 49


6.3.6. Lp trnh s dng DataList ................................................................................................ 52
6.5. DetailView .................................................................................................................................. 58
6.5.1. Cc thnh phn ca DetailsView ...................................................................................... 58
6.5.2. To iu khin DetailsView .............................................................................................. 59
6.5.3. To ngun d liu cho DetailsView dng AccessDataSource ...................................... 59
6.5.4. Thit k giao din cho cc thnh phn trong DetailsView ............................................ 61
Chng 7: Khc ............................................................................................................................... 64
7.1. IIS ................................................................................................................................................. 64
7.1.1. Hng dn ci t IIS cho windows 2000, XP ............................................................... 64
7.1.3. Trang Web u tay.............................................................................................................. 68
7.1.4. Qun l trnh ch Web Server ........................................................................................... 70
7.2. Javascript trong ASP.NET ........................................................................................................ 73
7.3. AJAX ........................................................................................................................................... 84
7.3.1. Gii thiu ............................................................................................................................. 84
7.3.1.1 Tng quan v m hnh ng dng Web ........................................................................... 84
7.3.1.2 Gii thiu v AJAX .......................................................................................................... 85
7.3.2. K thut lp trnh AJAX .................................................................................................... 86
7.3.2.1. X l h khch (Client) ................................................................................................... 86
7.3.2.2. X l h phc v (Server) .............................................................................................. 88
7.3.3. V d ..................................................................................................................................... 89
7.4. Web Service ................................................................................................................................ 94
7.4.1. Gii thiu ............................................................................................................................. 94
7.4.2. c im .............................................................................................................................. 95
7.4.3. Kin trc ca Web Services............................................................................................... 95
7.4.4. Cc thnh phn ca Web Service...................................................................................... 95
7.4.5. V d xy dng web service n gin .............................................................................. 96

Chng 1: Gii thiu ASP.NET


1.1. Gii thiu
ASP.NET l cng ngh x l web pha my ch , c l p vi mo i trin h duy t ,
K thut p du ng la cho phe p mo i thc thi c thc hi n trinh chu , tc la trinh chu phai x
l nhiu vn cng lc cho nhiu ngi dng trnh ch phi co cu hnh mnh v bng
thng t t . Tng thic h vi asp 3.0
1.2. Xy dng ng dng web n gin

1.2.1. To ng dng web


- Vo menu Start -> Programs -> Microsoft Visual Studio 2005 -> Microsoft Visual
Studio 2005
- Giao din Visual Studio 2005 co dng nh sau:

- Vo menu File->New->Website

- Chn ASP.NET Web Site trong Templates.

Cui cng click chut vo nt OK tin hnh to Web Site.

1.2.1.1. Thit k giao din


* Thit k giao din ch Source
- S dng cc th HTML thit k
- Trong ch th @Page cc thuc tnh:
+ Language : ngn ng s dng
+ CodeFile : tp tin m ngun x l
+ Inherits : lp

* Thit k giao din ch Design


- S dng cc control trn thanh cng c Toolbox thit k
- Thanh cng c Toolbox bao gm tp hp cc iu khin web (web control) dng
xy dng ng dng web chia ra thnh cc nhm control sau:
+ Standard: l nhng iu khin chun ca web form nh: Label, Button,
TextBox ...
+ Data: l nhng iu khin cho php thao tc vi d liu
+ Validation: l nhng iu khin cho php kim tra tnh hp l ca cc iu
khin nhp d liu trn web form.
+ Navigation: l nhng iu khin cho php di chuyn gia cc trang trong
cng website.
+ Login: l nhng iu khin lin quan n bo mt ca ng dng web nh ng
nhp, thay i mt khu,
+ HTML: l nhng iu khin ca ti liu HTML v co th c chuyn thnh cc
iu khin lm vic trn server (HTML Server Control)

1.2.1.2. M ngun x l
- Phng thc Page_Load c gi mi khi trang .aspx c ti (load).
- Giao din m ngun ch Code C#:

1.2.2. Lu li trang web


lu li cc trang web to trong website, vo menu File -> Save All hoc nhn t
hp phm Ctrl+Shift+S.

Nu mt s trang web co s dng ch Ting Vit Unicode th trong qu trnh lu cc trang


web, Visual Studio s yu cu lu li trang web vi kiu m ho Unicode.
Chn Save With Other Encoding

Trong Encoding chn Unicode (UTF-8 with signature) Codepage 65001

1.2.3. Bin dch v chy ng dng web


bin dch v chy ng dng web vo menu Debug -> Start Debugging hoc nhn
phm F5

1.2.4. M ng dng Web


m mt ng dng web, vo menu File -> Open -> Website

10

1.2.5. Thm trang web mi


Trong Solution Explorer, click phi vo Website, chn Add New Item

Trong Templates, chn Web Form, sau o nhp tn trang web vo Name v click vo
OK.

Lu :
11

Nu chn Place code in separate file th tp tin m ngun x l s c tch ring


khi tp tin Web Form.
1.3. IsPostBack
Thuc tnh IsPostBack:
+ Thuc tnh ca Page co kiu d liu bool (true, false)
+ Nu tr v gi tr false khi trang c np ln u tin.
+ Nu tr v gi tr true khi trang c np ln tip theo.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//cc cu lnh ch mun thc thi 1 ln khi trang c np ln u tin
}
}

Ghi ch:
Trong biu thc logic ca cu trc if trn
!IsPostBack tng ng vi IsPostBack == false

12

Chng 2: Web Control


2.1. Gii thiu
2.2. HTML Server Control

2.3. ASP.NET Web Control

2.3.1. Label (<asp:Label>)


Thuc tnh
ID
Text
Visible
Trang aspx:

Din gii
Nhn dng iu khin
Ni dung hin thi
Cho php hin th hay khng (true/false)

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Trang aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "xin cho";
}

2.3.2. TextBox (<asp:TextBox>)


Thuc tnh
TextMode
AutoPostBack
AutoCompleteType
Focus()

Din gii
SingleLine(mc
nh),
Multiline
(rows,columns), Password.
T ng PostBack ln Server khi Textbox co
thay i, mc nh l False
None / Disabled / Company /

2.3.3. Button (<asp:Button>)


Tng ng th <input> co type=submit
Trang aspx:
<asp:Button ID="txtLuu" runat="server" Text="Lu"
Font-Size="16pt" />

2.3.4. RadioButton (<asp:RadioButton>)


Thuc tnh

Din gii
13

GroupName
Trang aspx:
<asp:RadioButton
Text="N" />
<asp:RadioButton
Text="Nam" />

Nhom cc radio cng b


ID="RadioButton1"

runat="server"

GroupName="Phai"

ID="RadioButton2"

runat="server"

GroupName="Phai"

2.3.5. HyperLink (<asp:HyperLink>)


Thuc tnh
ImageUrl
NavigateUrl

Din gii
ng dn hnh nh lm nhn lin kt
ng dn lin kt

2.3.6. Calendar (<asp:Calendar>)

Trang aspx:
<asp:Calendar ID="Calendar1" runat="server"
OnSelectionChanged="Calendar1_SelectionChanged"> </asp:Calendar>

Trang aspx.cs:
protected void Calendar1_SelectionChanged(object sender,
EventArgs e)
{
Label1.Text = Calendar1.SelectedDate.ToString();
}

2.3.7. CheckBox (<asp:CheckBox>)


Thuc tnh:
ID: nh danh
Text: ni dung hin th
Checked: cho bit trng thi ca mc chn (co c chn hay khng)
AutoPostBack: thuc tnh ny cho bit co c php t ng PostBack v Server
khi cc mc chn ca iu khin b thay i. Ga tr mc nh ca thuc tnh ny l false
(khng t ng PostBack)
14

* Trang aspx
<asp:Label ID="Label1" runat="server">S thch:</asp:Label><br />
<asp:CheckBox ID="SoThich1" runat="server" Text="Th thao" />
<asp:CheckBox ID="SoThich2" runat="server" Text="Nghe nhc" />
<asp:CheckBox ID="SoThich3" runat="server" Text="Xem phim" />
<br />
<br />
<asp:Button ID="btn_Chon" runat="server" Text="Chn"
OnClick="btn_Chon_Click" />
<br />
<div id="txt_HienThi" runat="server"/>

* Trang aspx.cs
protected void btn_Chon_Click(object sender, EventArgs e)
{
string s;
s = "";
if (SoThich1.Checked == true)
s = s + SoThich1.Text + " ";
if (SoThich2.Checked == true)
s = s + SoThich2.Text + " ";
if (SoThich3.Checked == true)
s = s + SoThich3.Text;
//Xut kt qu
txt_HienThi.InnerText = s;
}

2.3.8. Image (<asp:Image>)

15

Trang aspx
<asp:Image ID="Image1" runat="server"
ImageUrl="~/BaiGiang3/Hinh/Garden.jpg" Height="228px" Width="306px" />

2.4. ASP.NET List Control


Thuc tnh

Din gii

AutoPostBack

false: Khi ngi dng thay i gi tr ca ListControl

DataSource
DataTextField
DataValueField

th trang web s khng c triu gi cho n khi dng


submit.
True: Trang web s submit mi khi ngi dng thay i gi
tr ca ListControl.
Gn hay tr v i tng cha d liu.
Gn hay tr v tn trng cung cp nhn cho ListControl
Gn hay tr v tn trng cung cp gi tr cho
ListControl

SelectedIndex

SelectedItem
SelectedValue
Items

Gn hay tr v ch s ca phn t c chn trong


ListControl. Trng hp chn nhiu phn t phi s
dng thuc tnh Selected ca i tng ListItem.
Tr v phn t c chn trong ListControl.
Tr v gi tr ca phn t c chn trong ListControl.
Tr v tp cc gi tr ca cc phn t trong ListControl

2.4.1. RadioButtonList (<asp:RadioButtonList>)


Trang aspx:
<form id="form1" runat="server">

16

<asp:RadioButtonList ID="RadioButtonList1" runat="server"


RepeatDirection="Horizontal">
<asp:ListItem Value="1">Nam</asp:ListItem>
<asp:ListItem Value="0">N</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Button" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>

Trang aspx.cs:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = RadioButtonList1.SelectedValue;
}

2.4.2. DropDownList (<asp:DropDownList>)


Trang aspx:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>Chn h</asp:ListItem>
<asp:ListItem Value="0">Cao ng</asp:ListItem>
<asp:ListItem Value="1">Trung cp</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" Visible="False">
</asp:DropDownList>

Trang aspx.cs:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)

{
string[] C = new string[4] {"CTH", "CCK","CT","CVT"};
string[] T = new string[3] {"TCTH","TCCK","TCKT"};
if (DropDownList1.SelectedValue == "0") {
DropDownList2.DataSource = C; }
else
DropDownList2.DataSource = T;
DropDownList2.DataBind();
DropDownList2.Visible = true;
}

2.4.3. CheckBoxList (<asp:CheckBoxList>)

17

Trang aspx
<asp:CheckBoxList ID="cbl_SoThich" runat="server"
RepeatDirection="Horizontal">
<asp:ListItem Value="0">Th thao</asp:ListItem>
<asp:ListItem Value="1">Nghe nhc</asp:ListItem>
<asp:ListItem Value="2">Xem phim</asp:ListItem>
</asp:CheckBoxList><br />
<asp:Button ID="btn_Chon" runat="server" Text="Chn"
OnClick="btn_Chon_Click"/>
<br />
<br />
<div id="txt_HienThi" runat="server"/>

Trang aspx.cs
protected void btn_Chon_Click(object sender, EventArgs e)
{
string s;
s = "";
foreach (ListItem list in cbl_SoThich.Items)
{
if (list.Selected == true)
s = s + list.Text;
}
txt_HienThi.InnerText = "S thch:" + s;
}

2.4.4. ListBox (<asp:ListBox>)


Thuc tnh

Din gii
18

SelectionMode

Single/Multiple: chn mt/nhiu phn t cng lc.

Trang aspx:
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>

Trang aspx.cs:
for (int i = 1; i <= 12; i++)
{
ListBox1.Items.Add(i.ToString());
}

Trang aspx:
S thch:
<asp:ListBox ID="ListBox1" runat="server" Rows="6"
SelectionMode="Multiple">
<asp:ListItem>Xem phim</asp:ListItem>
<asp:ListItem>Th thao</asp:ListItem>
<asp:ListItem>Du lch</asp:ListItem>
<asp:ListItem>Nghe nhc</asp:ListItem>
<asp:ListItem>Kh&#225;c</asp:ListItem>
</asp:ListBox>

Trang aspx.cs:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Bn chn:";
foreach (ListItem li in ListBox1.Items)
{
if (li.Selected == true)
Label1.Text += li.Text + " ";
}
}

2.5. FileUpload Control (<asp:FileUpload>)


Trang aspx:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"

Text="Lu" />

Trang aspx.cs:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
FileUpload1.SaveAs(Server.MapPath("hinh")+"\\" +FileUpload1.FileName);
}

Kch thc tp tin upload gii hn l: 4MB (4096KB). Co th thay i gii hn ny nh sau:
Trong tp tin Web.config thm trong th <system.web>
19

<httpRuntime

executionTimeout="90"

maxRequestLength="4096"

/>

2.6. ASP.NET Validation Control


Kim tra tnh hp l ca d liu nhp vo form, vic kim tra c thc hin khi nhp vo
Button trong form. Nu mun b qua tc dng ca Validation Control khi nhn vo Butto n
th chn thuc tnh CausesValidation = false.
Thuc tnh chung
ControlToValidate: gn/tr v tn iu khin cn kim tra
ErrorMessage: chui li pht sinh nu kim tra khng hp l.
Enabled: gn/tr v gi tr Boolean ch ra rng nu qu trnh kim tra gi tr ca iu
khin c thc hin. Gn True nu mun kim tra d liu nhp bng cc Validation
Control, false v hiu hoa qu trnh kim tra.
EnableClientScript: gn/tr v gi tr Boolean ch ra rng cho php kim tra gi tr
ca iu khin trn pha trnh khch (JavaScript)

2.6.1. RequiredFieldValidator
Kim tra iu khin khng c rng.
Trang aspx:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ControlToValidate="txtTen" ErrorMessage="cha nhp">
</asp:RequiredFieldValidator>

2.6.2. RangeValidator
Kim tra iu khin phi l chui, s, ngy, . Nu rng th khng kim tra.
Thuc tnh: MaximumValue, MinimumValue, Type (String, Interger, Date, ),
Trang aspx:
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="T 1 n 10 triu"
MaximumValue="10000000" MinimumValue="1" > </asp:RangeValidator>

2.6.3. CompareValidator
So snh iu khin ny vi iu khin khc hay mt gi tr c th. Nu rng th khng
kim tra.
Thuc tnh: ControlToCompare, Operator(Equal, GreaterThan, LessThan, ), Type,
ValueToCompare,

Trang aspx:
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToCompare="txtMatKhau" ControlToValidate="txtMatKhauLai"
ErrorMessage="khng ging " Display="Dynamic">
</asp:CompareValidator>
20

2.6.4. RegularExpressionValidator
Kim tra gi tr trong iu khin phi ph hp vi gi tr cho trc. Nu rng th
khng kim tra.
Thuc tnh: ValidationExpression,
Trang aspx:
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server" ControlToValidate="txtEmail" ErrorMessage="khng hp
l"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([.]\w+)*">
</asp:RegularExpressionValidator>

2.6.5. CustomValidator
Thc hin kim tra do ngi dng t nh ngha.
Thuc tnh: ClientValidationFunction, OnServerValidation

2.6.6. ValidationSummary
Tp hp cc thng bo li.
Thuc tnh: DisplayMode, ShowMessageBox, ShowSummary,

21

Chng 3: Master Page, CSS, User Control


3.1. Master Page v Style Sheet

3.1.1 Gii thiu v Master Page


Mt Website chuyn nghip cn mt khung nhn v cm gic nht qun lm cho ngi
dng bit h ang u trong website cng nh d dng chuyn t trang ny sang trang
khc. (tham kho thm ti liu 7 bc thit k web hiu qu tc gi L nh Duy)
Master Page l cch tt gip cho website co khung nhn nht qun. V cho php ta
nh ngha v tr xut hin ca phn ni dung trn mi trang.
Master Page cn cho php ta nh ngha cc nh dng chung cho tt c cc trang trn
cng mt website.
V d:
Cc hnh bn di cho cho thy mt khung nhn chung cho cc trang. Vng mu xm
s l vng ging nhau mi trang. Vng mu trng l vng phn bit ca mi trang.

3.1.2 To trang Master page


3.1.2.1 To th mc cho trang Master Page
To mt th mc trn Website gip d qun l cc tp tin thit k, m ngun.
Maste Page nn t trong 1 th mc ca Website.
Thc hin:
Click phi chut trn Solution Explorer, chn New Folder
3.1.2.2 To trang Master Page
Cc bc thc hin:
22

1. Trong Solution Explorer, click phi chut vo th mc mun t trang Master


Page v chn Add New Item.
2. Trong hp thoi Add New Item, click Master Page.
3. Nhp tn tn trang Master Page (co th tn mc nh l: MasterPage.master)
4. Chn ngn ng lp trnh (C#/VB.NET)
5. Chn check box Place code in separate file.
6. Click vo nt Add.

3.1.2.3 Thit k trang layout


Cc bc thc hin:
1. T mn hnh thit k, chn LayoutInsert Table.
2. Trong hp thoi Insert Table, chn Template
3. Chn mt template t drop-down list.
4. Click OK.

23

ContentPlaceHolder: ni cha ni dung ring ca tng trang web.


Layout ca trang ch l 1 table, mi khung nhn (layout) ch l mt cell trong bng
c nh ngha bng cp th <td> v </td> trong HTML. Co th xem source HTML bng
cch click vo nt Source.

3.1.3. Cascading Style Sheets (CSS)


Cascading Style Sheets (CSS) l mt c ch n gin dng cho vic thm cc nh dng
(style) (nh font, mu, khong cch ) cho mt trang Web.

3.1.3.1. Dng Style cho Master Page


Mi khung (pane) ca trang Master Page l mt cell trong bng. Do o, ta co th nh
dng cho mi khung (pane) ca trang Master Page.
Thc hin:
1. Click phi chut vo khung (pane) mun nh dng chn Style.
2. Hp thoi Style Builder xut hin, tin hnh nh dng cho khung.

24

Mt s style:
Font
Background
Text
Position
Layout
Edges
List
Others
3.1.3.2. Dng Style cho ContentPlaceHolder
Click phi chut vo vng trng nm ngoi khung ContentPlaceHolder, chn Style

3.1.4. S dng trang Master Page


s dng Master Page, ta to mt Web Form mi.
Cc bc thc hin:

25

1. Click phi chut vo tn Website trn Solution Explorer v chn Add New Item.
2. Trong hp thoi Add New Item, chn Web Form.
3. Trong Name, nhp trn trang Web.
4. Chn vo checkbox Select Master Page.
5. Click vo nt Add.
6. Trong hp thoi Select a Master page, chn trang Master Page.
7. Click OK.

26

Cu hi:
1. B sung trang Master Page cho mt trang Web co sn
2. Vn chn hnh vo Master Page, Web Form

3.2. Web User Control


Web User Control l iu khin do ngi dng t nh ngha ring dng chc nng
ho (functionality) mt control m khng c cung cp sn trong ASP.NET. Ta co th
design v xy dng ging nh mt Web Form.

3.2.1 To mt Web User Control


to mt Web User ta thc hin nh sau:
1. Trong Solution Explorer, click phi chut vo Solution chn Add New Item.
2. Trong hp thoi Add New Item, chn Web User Control
3. Nhp vo Name tn ca tp tin Web User Control.
4. Chn ngn ng (VB.NET/C#)
5. Click vo nt Add.

27

3.2.2 S dng Web User Control


Ko th Web User Control t Solution Explorer vo trang Web ang thit k (chng hn
Master Page, Web Form, )

28

Chng 4: Cc i tng trong ASP.NET


4.1. ViewState
Lu thng tin ca mi WebForm do Ser ver qun l, cha thng tin ca tt c cc ngi dng
trong trang. Khi tr v cho trnh khch, ViewState c trnh by di dng th hidden v
co gi tr c m hoa. Co th v hiu hoa hay cho php viewstate bng cch s dng thuc
tnh EnableViewState trong tng th hay trong trang cu hnh ca ng dng.
V d

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
ViewState["dem"] = 1;
else
ViewState["dem"] = (int)ViewState["dem"]+1;
Label1.Text = "ln load " +ViewState["dem"];
}

4.2. Response
HttpResponse c dng chuyn d liu t Server v Client
Gi tt c thng tin x l cho cc client, chng ta co th s dng i tng ny giao tip
vi ngi dng.
Phng thc
Write: xut thng tin dng chui ra trang web, khng th qui nh v tr xut.
Redirect: chuyn sang a ch khc.
WriteFile: ghi lung d liu ra tp tin.
Clear, end, flush

V d
Response.write (str)
Response.write (str)
Response.Redirect("abc.aspx")

4.3. Request
HttpRequest c dng chuyn d liu t Client v Server.
Nhn tt c gi tr m trnh duyt ca client gi n server thng qua mt yu cu HTTP
request.

29

V d 1
<asp:HyperLink ID="HyperLink1" runat="server">HyperLink</asp:HyperLink>
protected void Page_Load(object sender, EventArgs e)
{
HyperLink1.NavigateUrl = "a.aspx?x=111&y=222";
}

protected void Page_Load(object sender, EventArgs e)


{
string i;
i = Request.QueryString.Get ("x") ;
Response.Write(i+"<br>");
i = Request.QueryString.Get("y");
Response.Write(i);
}

V d 2
Response.Write(Request.Browser.Browser + "<br>");
Response.Write(Request.Browser.Version + "<br>");
Response.Write(Request.Browser.Platform + "<br>");
Response.Write(Request.Browser.JavaScript + "<br>");

4.4. Application
Application c dng qun l tt c cc thng tin ca 1 website. Mt bin nu c

khai bo trong 1 trang web, no s b hy ngay khi Server x l xong trang ny. co th khai
bo cc bin s dng cho nhiu trang hay nhiu ln x l trang co th s dng i tng
Application. D liu lu trong Application s c chia s cho tan b ng dng, tan
b ngi dng v co th tn ti trong c chu trnh sng ca website.

4.5. Session
Session c dng lu tr cc thng tin dng cho mt phin lm vic ca mt ngi

dng. Cc bin c lu tr trong i tng ny s khng b hy khi ngi dng chuyn t


trang ny sang trang khc. Lu cc thng tin ring bit cho tng phin lm vic. Khi ngi
dng yu cu mt trang web t mt ng dng, Web server t ng to ra mt i tng
Session v i tng Session ny s t ng b hy khi ngi dng khng co yu cu gi

30

n Web server sau khong thi gian timeout. D liu lu trong Session s c chia s cho
tan b ng dng ca 1 ngi dng.
Thuc tnh TimeOut: t thi gian ht hn (tnh bng pht, mc nh l 20).
Phng thc Abandon: hy Session hin hnh ngay lp tc.
Tp tin global.asax:
Tp tin ny c dng khi cn khai bo v vit cc x l cho cc s kin ca bin
Application, Session.
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
}
</script>

4.6. Cookies
Cookies l i tng m Server dng lu thng tin ngi dng ngay ti my Client di dng tp
tin.
V d
if (Request.Browser.Cookies == true)
{
if (Request.Cookies["LastVisit"] == null)
{
HttpCookie cookie = new HttpCookie("LastVisit",
DateTime.Now.ToString());
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
Label2 .Text = "y l ln u tin bn truy cp website ny";
}
else
31

{
HttpCookie cookie = Request.Cookies["LastVisit"];
Label2.Text = "Ln cui bn truy cp l" + cookie.Value;
Response.Cookies["LastVisit"].Value = DateTime.Now.ToString();
Response.Cookies["LastVisit"].Expires = DateTime.Now.AddDays(1);
}
}
else
{
Label2.Text = "Trnh duyt khng h tr cookie";
}

4.7. Server
i tng Server thuc lp HttpServerUtility cung cp cc phng thc dng cho vic
x l cc yu cu t pha Server.
* Cc thuc tnh
STT

Tn thuc tnh

M t

V d

Tr v tn ca my
tnh server

Ly tn ca my tnh server:
string sComputerName;

MachineName

sComputerName = Server.MachineName;

2
ScriptTimeout

Gn hoc tr v thi
gian ti a nhn yu
cu (request) t
client (tnh bng
giy)

t gi tr thi gian ti a nhn yu cu t


client l 60 giy
Server. ScriptTimeout = 60;

* Cc phng thc quan trng


STT

Tn phng
thc

M t

V d

Tr v ng dn vt l ca Ly ng dn vt l ca th mc o
th mc o (virtual directory) MyWebSite trn my ch web:
trn my ch web

String FilePath;

MapPath

FilePath =
Server.MapPath("/MyWebSite");

32

M ho chui a ch URL
dng cho vic truyn t my
ch Web n client thng qua
giao thc HTTP.

V d minh ho vic m ho chui a


ch URL trc khi gi chui a ch
ny cho trnh duyt web client.
Chng hn, MyURL c m ho
thnh
"http%3a%2f%2fwww.abc.com%2far
ticles.aspx%3ftitle+%3d+ASP.NE
T+Examples"

UrlEncode

String MyURL;
MyURL =
"http://www.abc.com/articles.a
spx?title = ASP.NET Examples";
Response.Write( "<A HREF = " +
Server.UrlEncode(MyURL) + ">
ASP.NET Examples <br>" );

Gii m chui c m
ho t giao thc HTTP v
gi cho server bng a
ch URL.

V d minh ho vic gii m chui


EncodedString (c nhn trong a
ch URL) sang chui
DecodedString

UrlDecode
String DecodedString =
Server.UrlDecode(EncodedString
);

Ngng thc thi trang web M trang Index.aspx


hin hnh v bt u thc
thi (m) mt trang web
Server.Transfer("Index.aspx");
mi.

Transfer

Co chc nng tng t


nh: Response.Redirect.
Tuy nhin,
Server.Transfer ch
dng m 1 trang web
mi trong cng website
vi trang web hin ti.

33

4.8. Exception
- Exception l lp i tng dng by li trong sut qu trnh thc thi ng dng
(Windows, Web).
- Khi mt li xut hin trong khi thc thi ng dng, th h thng cng nh ng dng
ang thc thi s thng bo thng tin v li thng qua Exception.
- Exception thng kt hp vi lnh trycatch
- Thuc tnh quan trng:
+ Message: Cho bit m t thng tin v li.
V d: Xy dng trang web tnh bnh phng ca 1 s nguyn.

Trang .aspx:
<asp:Label ID="Label1" runat="server" Text="n:"></asp:Label>
<asp:TextBox ID="txt_n" runat="server"></asp:TextBox><br />
<asp:Button ID="btn_TinhBinhPhuong" runat="server" Text="Bnh phng"
OnClick="btn_TinhBinhPhuong_Click" /><br />
<br />
<asp:Label ID="lb_KetQua" runat="server"></asp:Label></div>

Trang .aspx.cs
protected void btn_TinhBinhPhuong_Click(object sender, EventArgs e)
{
string s;
int n;
int kq;
try
{
s = txt_n.Text;
//chuyn t chui sang s nguyn
n = int.Parse(s);
//bnh phng
kq = n * n;

34

//xut kt qu
lb_KetQua.Text = kq.ToString();
}
catch (Exception ex)
{
//Nu xy ra li th xut thng bo li
lb_KetQua.Text = ex.Message;
}
}

Nu nhp n ="abc" th xut hin thng bo li. V n khng phi l s nguyn.

35

Chng 5: Kt ni d liu vi ADO.NET


5.1. Gii thiu
i tng ADO.NET c thit k nh mt cng ngh truy xut d liu khng kt ni v phn phi
da trn chun XML, tng tc truy cp v thao tc d liu trong mi trng a lp (N -Tier). Hai
thnh phn chnh l i tng DataSet v .NET Provider.
ADO.NET chia lm hai loi: lp kt ni Connected Layer v lp khng kt ni Disconnected Layer,
hai lp ny c s dng song song trong cng ng dng, thao tc trn CSDL nh SQL Server, My
SQL, MS Access, Oracle v c s d liu phn cp khc.
Khi mun s dng cc i tng ny, ty vo loi ngun d liu cn khai bo:
using System.Data.OleDb;
using System.Data.SqlClient;

Trong phn ny chng ta s lm cc v d trn bng d liu

5.2. Cc i tng trong ADO.NET

5.2.1. Connection
Thit lp kt ni gia ng dng vi ngun d liu
V d 1
string ChuoiKetNoi;
ChuoiKetNoi = "provider=microsoft.jet.oledb.4.0;Data Source=" + _
Server.MapPath("App_Data\\db1.mdb");
OleDbConnection c =new OleDbConnection (ChuoiKetNoi);
c.Open ();

V d 2
string ChuoiKetNoi;
ChuoiKetNoi = "server=localhost;UID=;PWD=;database=Sach;Integrated
Security=True;";
SqlConnection c =new SqlConnection (ChuoiKetNoi );
c.Open ();

5.2.2. Command
Thc thi cc cu lnh SQL hay Stored Procedure

5.2.2.1 Thuc tnh


Connection: cha i tng kt ni
CommandText: cha cu lnh SQL
Parameters: tp hp cc tham s

36

5.2.2.2 Phng thc


ExecuteReader: tr v i tng DataReader, c d liu tng

dng trc tip t ngun.


ExecuteScalar: thi hnh cu truy vn v ch tr v 1 gi tr ca ct

u tin ca dng u tin.


ExecuteNonQuery: gi thi hnh cc cu truy vn Insert, Update,
Delete v tr v s dng chu tc ng (nu khng co th tr v -1)
hoc gi thi hnh cc Stored Procedure khng co d liu tr v
nhng co th co cc tham s u ra.

V d
string ChuoiKetNoi;
ChuoiKetNoi = "provider=microsoft.jet.oledb.4.0;Data Source=" + _
Server.MapPath("App_Data\\db1.mdb");
OleDbConnection c =new OleDbConnection (ChuoiKetNoi );
c.Open ();
string ChuoiTruyVan;
ChuoiTruyVan = "select count(*) from ThanhVien";
OleDbCommand m = new OleDbCommand();
m.Connection = c;
m.CommandText = ChuoiTruyVan;
int n;
n = (int)m.ExecuteScalar();
Response.Write("s dng d liu:" + n);

5.2.3. DataReader
L lp ch c v d liu c theo mt chiu. Tit kim b nh v ti mt thi im ch lu tr mt
mu tin. Phng thc Read dng c mu tin, no t ng chuyn n mu tin k tip cho n khi
khng cn mu tin no, khng co khi nim nh hng EOF/BOF/Next/Previos
Thng c dng hin th d liu ra mn hnh 1 ln, kim tra d liu co tn ti hay khng.
V d 1
string ChuoiKetNoi;
ChuoiKetNoi = "provider=microsoft.jet.oledb.4.0;Data Source=" +
Server.MapPath("App_Data\\db1.mdb");
OleDbConnection c =new OleDbConnection (ChuoiKetNoi );
c.Open ();
string ChuoiTruyVan;
ChuoiTruyVan="select * from ThanhVien";
OleDbCommand m=new OleDbCommand();
m.Connection =c;
m.CommandText =ChuoiTruyVan ;
OleDbDataReader d;
d=m.ExecuteReader();
while (d.Read())
{
Response.Write("<br>Tn: ");
Response.Write(d["Ten"].ToString ());
}
d.Close();

V d 2
37

string ChuoiKetNoi;
ChuoiKetNoi = "server=localhost;UID=;PWD=;database=Sach;Integrated
Security=True;";
SqlConnection c =new SqlConnection (ChuoiKetNoi );
c.Open ();
string ChuoiTruyVan;
ChuoiTruyVan="select * from NhaXuatBan";
SqlCommand m=new SqlCommand();
m.Connection =c;
m.CommandText =ChuoiTruyVan ;
SqlDataReader d;
d=m.ExecuteReader();
while (d.Read())
{
Response.Write("<br>Tn: ");
Response.Write(d["TenNXB"].ToString ());
}
d.Close();

V d 1 truy xut d liu Access, v d 2 truy xut d liu SQLServer, so snh s khc nhau?

5.2.4. DataAdapter
Kt ni ngun d liu v in d liu vo b nh thng tr DataSet.
Thuc tnh: SelectCommand, InsertCommand, UpdateCommand, DeleteCommand tng ng cc
pht biu SQL dng thao tc d liu trn DataSet.
Phng thc Fill: thc thi SelectCommand v in d liu vo i tng DataSet.
Phng thc Update: gi i tng Command thc thi InsertCommand, UpdateCommand,
DeleteCommand.

5.2.5. DataSet
DataSet c xem nh nh ca mt ngun d liu thu nh co kh nng hot ng c lp khi ngt
kt ni. DataSet co th cha cc bng (DataTable), view (DataView), quan h (Relations), rng
buc (Contraints) nh mt Database tht s.

5.2.6. DataTable
5.2.7. DataView
5.3. Kt ni d liu trong ASP.NET

5.3.1. Thm

38

protected void Lu_Click(object sender, EventArgs e)


{
string ChuoiKetNoi;
ChuoiKetNoi = "provider=microsoft.jet.oledb.4.0;Data Source=" +
Server.MapPath("App_Data\\db1.mdb");
OleDbConnection c = new OleDbConnection(ChuoiKetNoi);
c.Open();
string ChuoiTruyVan;
OleDbCommand m = new OleDbCommand();
m.Connection = c;
m.Parameters.Add("a1",t1.Text);
m.Parameters.Add("a2",t2.Text);
m.Parameters.Add("a3",t4.Text);
if (t5.Text == "")
ChuoiTruyVan = "insert into ThanhVien(Ten,MatKhau,Email)
values(a1,a2,a3)";
else
{
m.Parameters.Add("a4", t5.Text);
ChuoiTruyVan = "insert into
ThanhVien(Ten,MatKhau,Email,SoDangKy) values(a1,a2,a3,a4)";
}
m.CommandText = ChuoiTruyVan;
try
{
m.ExecuteNonQuery();
c.Close();
Response.Redirect("KetNoiDuLieuAccess.aspx");
}
catch (Exception ex)
{
Response.Write("THNG BO LI" + ex.Message);
}
c.Close();
}

LU : TRNG KHA CHNH

5.3.2. Xo

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
string ChuoiKetNoi;
ChuoiKetNoi = "provider=microsoft.jet.oledb.4.0;Data Source="
+ Server.MapPath("App_Data\\db1.mdb");
OleDbConnection c = new OleDbConnection(ChuoiKetNoi);
39

c.Open();
string ChuoiTruyVan;
ChuoiTruyVan = "select * from ThanhVien";
OleDbCommand m = new OleDbCommand();
m.Connection = c;
m.CommandText = ChuoiTruyVan;
OleDbDataAdapter a = new OleDbDataAdapter();
a.SelectCommand = m;
DataSet d = new DataSet();
a.Fill(d);
DropDownList1.DataTextField = "Ten";
DropDownList1.DataValueField = "Ten";
DropDownList1.DataSource = d;
DropDownList1.DataBind();
c.Close();
}
}
protected void Xoa_Click(object sender, EventArgs e)
{
string t=DropDownList1.SelectedValue;
string ChuoiKetNoi;
ChuoiKetNoi = "provider=microsoft.jet.oledb.4.0;Data Source=" +
Server.MapPath("App_Data\\db1.mdb");
OleDbConnection c = new OleDbConnection(ChuoiKetNoi);
c.Open();
string ChuoiTruyVan;
ChuoiTruyVan = "delete * from ThanhVien where Ten=a1";
OleDbCommand m = new OleDbCommand();
m.Connection = c;
m.Parameters.Add("a1", t);
m.CommandText = ChuoiTruyVan;
try
{
m.ExecuteNonQuery();
c.Close();
Response.Redirect("KetNoiDuLieuAccess.aspx");
}
catch (Exception ex)
{
Response.Write("THNG BO LI" + ex.Message);
}
c.Close();
}

5.3.3. Hiu chnh

40

protected void HienThi_Click(object sender, EventArgs e)


{
Lu.Visible = false;
CapNhat.Visible = true;
t1.Enabled = false;
string t = DropDownList1.SelectedValue;
string ChuoiKetNoi;
ChuoiKetNoi = "provider=microsoft.jet.oledb.4.0;Data Source=" +
Server.MapPath("App_Data\\db1.mdb");
OleDbConnection c = new OleDbConnection(ChuoiKetNoi);
c.Open();
string ChuoiTruyVan;
ChuoiTruyVan = "select * from ThanhVien where Ten=a1";
OleDbCommand m = new OleDbCommand();
m.Connection = c;
m.Parameters.Add("a1", t);
m.CommandText = ChuoiTruyVan;
OleDbDataReader d;
d = m.ExecuteReader();
while (d.Read())
{
t1.Text =d["Ten"].ToString();
t4.Text = d["Email"].ToString();
t5.Text = d["SoDangKy"].ToString();
}
d.Close();
c.Close();
}
protected void CapNhat_Click(object sender, EventArgs e)
{
string ChuoiKetNoi;
ChuoiKetNoi = "provider=microsoft.jet.oledb.4.0;Data Source=" +
Server.MapPath("App_Data\\db1.mdb");
OleDbConnection c = new OleDbConnection(ChuoiKetNoi);
c.Open();
string ChuoiTruyVan;
ChuoiTruyVan = "update ThanhVien set Email=a1,SoDangKy=a2 where
Ten=a3";
OleDbCommand m = new OleDbCommand();
m.Connection = c;
m.Parameters.Add("a1", t4.Text);
m.Parameters.Add("a2", t5.Text);
m.Parameters.Add("a3", t1.Text);
m.CommandText = ChuoiTruyVan;
try
{
m.ExecuteNonQuery();
c.Close();
Response.Redirect("KetNoiDuLieuAccess.aspx");
}
41

catch (Exception ex)


{
Response.Write("THNG BO LI" + ex.Message);
}
c.Close();
}

42

Chng 6: iu khin lin kt d liu


6.1. Gii thiu

6.2. GridView
Cho php hin th d liu dng bng, kt qu xut ra trnh duyt l th <table>. Co th: phn trang;
sp xp tng ct d liu; chn, xoa, cp nht tng dng d liu.
To 1 GridView: Toolbox->nhp i chut vo GridView
To ngun d liu cho GridView
Bc 1: nhp chut

Bc 2: chn

Bc 3: Chn AccessData kt ni vi file d liu Access->OK


Bc 4: ng dn n file d liu->Next

43

Bc 5: Chn cch ly d liu ->Next


Bc 6: Co th Kim tra th d liu ly c->Finish
Hiu chnh cch hin th d liu:

nh dng hnh thc: chn Auto Format hoc Properties->Styles


nh dng ni dung: Chn Edit Columns

Thuc tnh DataFormatString: (Lu thuc tnh HTMLEncode)


V d: DataFormatString="{0:dd/MM/yy}"

44

Sp xp d liu theo ct
Gn thuc tnh ca GridView: AllowSorting=True
Gn thuc tnh ca cc ct mun sp xp: SortExpression=TnCt
Phn trang d liu
Gn thuc tnh ca GridView: AllowPaging=True, PageSize=s lng mu tin
trong 1 trang

Th PagerSettings: nh dng hnh thc hin th


Position=Top/Bottom/TopandBottom
Mode=Numeric/NumericFirstLast/NextPrevious/NextPreviousFirstLast
PageButtonCount =s trang hin th ti a, nu s trang nhiu hn s ny th s hin th tng

phn

6.3. DataList
DataList control l iu khin dng hin th d liu trn Web, khi s dng DataList control
chng ta phi t thit k cch thc hin th d liu.
V d:
45

6.3.1. Cc thnh phn ca DataList


<html>
<body>
<form runat="server">
<asp:DataList id="myDataList" runat="server">
<HeaderTemplate>
...
</HeaderTemplate>
<ItemTemplate>
...
</ItemTemplate>
<FooterTemplate>
...
</FooterTemplate>
</asp:DataList>
</form>
</body>
</html>

6.3.2. To iu khin DataList


Trn thanh ToolBox nhp chut chn DataList vo ko th vo giao din thit k Web Form

46

6.3.3. To ngun d liu cho DataList dng AccessDataSource

Bc 1: nhp chut
Bc 2: chn

47

Bc 3: Chn AccessData kt ni vi file d liu Access->OK


Bc 4: ng dn n file d liu->Next
Bc 5: Chn cch ly d liu ->Next

Bc 6: Co th Kim tra th d liu ly c->Finish

6.3.4. Thit k giao din cho cc thnh phn trong DataList

48

Bc 1: nhp chut

Thit k giao din trong vng ItemTemplate

6.3.5. Lin kt d liu cho cc thnh phn trong DataList

49

Bc 2: chn

Bc 1: nhp chut

Thc hin tng t nh trn i vi Mt khu, email, s ng k.

50

Bc 2: chn

<asp:DataList ID="DataList1" runat="server"


DataSourceID="AccessDataSource1">
<ItemTemplate>
<br />
<table border="1">
<tr>
<td style="width: 86px">
<asp:Label ID="Label1" runat="server"
Text="Tn"></asp:Label></td>
<td style="width: 100px">
<asp:Label ID="lb_Ten" runat="server"
Text='<%# Eval("ten") %>'></asp:Label></td>
</tr>
<tr>
<td style="width: 86px">
<asp:Label ID="Label2" runat="server" Text="Mt khu">
</asp:Label></td>
<td style="width: 100px">
<asp:Label ID="lb_MatKhau" runat="server"
Text='<%# Eval("matkhau") %>'></asp:Label></td>
</tr>
<tr>
<td style="width: 86px; height: 21px">
<asp:Label ID="Label3" runat="server"
Text "Email"></asp:Label></td>
<td style="width: 100px; height: 21px">
<asp:Label ID="lb_Email" runat="server"
Text='<%# Eval("email") %>'></asp:Label></td>
</tr>
<tr>
<td style="width: 86px">
<asp:Label ID="Label4" runat="server"
Text="S ng k"></asp:Label></td>
<td style="width: 100px">
<asp:Label ID="lb_SoDangKy" runat="server"
Text='<%# Eval("sodangky") %>'></asp:Label></td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/db1.mdb"
SelectCommand="SELECT `ten`, `matkhau`, `email`, `sodangky` FROM
`ThanhVien`"
UpdateCommand="UPDATE `ThanhVien` SET `matkhau` = ?, `email` = ?,
`sodangky` = ? WHERE `ten` = ?">
<UpdateParameters>
<asp:Parameter Name="matkhau" Type="String" />
<asp:Parameter Name="email" Type="String" />
<asp:Parameter Name="sodangky" Type="Int32" />
<asp:Parameter Name="ten" Type="String" />
</UpdateParameters>
</asp:AccessDataSource>

51

Kt qu:

6.3.6. Lp trnh s dng DataList


V d:
Xy dng trang web nghe nhc n gin vi c s d liu cho sn
Hy thc hin cc yu cu sau s dng DataList control:
a) Hin th danh sch tt c bi ht (DSBaiHat.aspx)
b) Hin th chi tit thng tin bi ht (CTBaiHat.aspx)
C s d liu:

52

a) Hin th danh sch tt c bi ht (DSBaiHat.aspx)

M ngun minh ho:

53

DSBaiHat.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DSBaiHat.aspx.cs"
Inherits="DSBaiHat" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="dlBaiHat" runat="server" GridLines="Both">
<HeaderTemplate>
<td>M Bi Ht</td>
<td>Tn Bi Ht</td>
<td>Tn Nhc S Sng Tc</td>
</HeaderTemplate>
<ItemTemplate>
<td><%#DataBinder.Eval(Container.DataItem,"MaBaiHat") %></td>
<td><a href='<%#"CTBaiHat.aspx?MaBaiHat="+
DataBinder.Eval(Container.DataItem,"MaBaiHat")
%>'>
<%#DataBinder.Eval(Container.DataItem,"TenBaiHat")
%></a></td>
<td><%#DataBinder.Eval(Container.DataItem,"TenNhacSi") %></td>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>

Ghi ch:
- Biu thc databinding <%# biu_thc %> c dng b sung thm on m ngun
trong trang web ca ngn ng nh VB.NET, C#.
- DataBinder.Eval (Object, String): dng nh gi (evalutate) li biu thc
databinding vi mt i tng (Object) ti thi im runtime
- Container.DataItem: l nh danh ti thi im runtime cho DataItem.
DSBaiHat.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Data;
public partial class DSBaiHat : System.Web.UI.Page
54

{
public DataSet LayDanhSachBaiHat()
{
DataSet ds;
ds = new DataSet();
string sConnectString;
string sSql;
sConnectString = "Provider=Microsoft.Jet.OleDB.4.0;Data Source=" +
Server.MapPath("DB/MusicDB.mdb");
OleDbConnection myConn = new OleDbConnection(sConnectString);
sSql = "SELECT
MaBaiHat,TenBaiHat,NoiDung,TenNhacSi,BaiHat.MaNhacSi as MaNS FROM
BaiHat,NhacSi WHERE BaiHat.MaNhacSi=NhacSi.MaNhacSi";
try
{
myConn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(sSql, myConn);
da.Fill(ds);
myConn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
return ds;
}
public void HienThiDanhSachBaiHat()
{
try
{
DataSet ds;
ds = new DataSet();
ds = LayDanhSachBaiHat();
dlBaiHat.DataSource = ds.Tables[0];
dlBaiHat.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void Page_Load(object sender, EventArgs e)
{
HienThiDanhSachBaiHat();
}
}

b) Hin th chi tit thng tin bi ht (CTBaiHat.aspx)


55

M ngun minh ho:


CTBaiHat.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CTBaiHat.aspx.cs"
Inherits="CTBaiHat" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="dlBaiHat" runat="server" GridLines="Both">
<HeaderTemplate>
<td>
<B>Thng tin bi ht</B>
</td>
</HeaderTemplate>
<ItemTemplate>
<td>
<B>M bi ht:</B>
<%#DataBinder.Eval(Container.DataItem,"MaBaiHat") %>
</br><B>Tn bi ht:</B>
<%#DataBinder.Eval(Container.DataItem,"TenBaiHat") %>
</br><B>Ni dung bi ht:</br></B>
<%#DataBinder.Eval(Container.DataItem,"NoiDung") %>
</br><B>Nhc s sng tc:</B>
<a href='<%#"CTNhacSi.aspx?MaNhacSi="+
DataBinder.Eval(Container.DataItem,"MaNS") %>'>
56

<%#DataBinder.Eval(Container.DataItem,"TenNhacSi") %></a>
</td>
</ItemTemplate>
</asp:DataList><br />
</div>
</form>
</body>
</html>

CTBaiHat.aspx.cs
using
using
using
using
using
using
using
using
using
using
using
using

System;
System.Data;
System.Configuration;
System.Collections;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Web.UI.HtmlControls;
System.Data;
System.Data.OleDb;

public partial class CTBaiHat : System.Web.UI.Page


{
public DataSet LayThongTinBaiHat(string sMaBaiHat)
{
DataSet ds;
ds = new DataSet();
string sConnectString;
string sSql;
sConnectString = "Provider=Microsoft.Jet.OleDB.4.0;Data Source=" +
Server.MapPath("DB/MusicDB.mdb");
OleDbConnection myConn = new OleDbConnection(sConnectString);
sSql = "SELECT
MaBaiHat,TenBaiHat,NoiDung,TenNhacSi,BaiHat.MaNhacSi as MaNS FROM
BaiHat,NhacSi WHERE BaiHat.MaNhacSi=NhacSi.MaNhacSi ";
sSql += "AND MaBaiHat='" + sMaBaiHat + "'";
try
{
myConn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(sSql, myConn);
da.Fill(ds);
myConn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
57

return ds;
}
public void HienThiChiTietBaiHat(string sMaBaiHat)
{
try
{
DataSet ds;
ds = new DataSet();
ds = LayThongTinBaiHat(sMaBaiHat);
dlBaiHat.DataSource = ds.Tables[0];
dlBaiHat.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void Page_Load(object sender, EventArgs e)
{
string sMaBaiHat;
if (Request.QueryString["MaBaiHat"] != null)
{
sMaBaiHat = Request.QueryString["MaBaiHat"];
HienThiChiTietBaiHat(sMaBaiHat);
}
}
}

6.5. DetailView
DetailsView l iu khin cho php hin th mt mu tin hoc mt i tng ti mt im.
V d:

6.5.1. Cc thnh phn ca DetailsView

58

<asp:DetailsView ID="DetailsView1" runat="server"


AllowPaging="True"
AutoGenerateRows="False" DataKeyNames="ten"
DataSourceID="AccessDataSource1" Height="50px" Width="250px">
<Fields>
<asp:BoundField DataField="ten" HeaderText="Tn"
ReadOnly="True"
SortExpression="ten" />
. . .
</Fields>
</asp:DetailsView>

6.5.2. To iu khin DetailsView


Trn thanh ToolBox nhp chut chn DetailsView vo ko th vo giao din thit k Web
Form

6.5.3. To ngun d liu cho DetailsView dng AccessDataSource

59

Bc 1: nhp chut

Bc 3: Chn AccessData kt ni vi file d liu Access->OK


Bc 4: ng dn n file d liu->Next
Bc 5: Chn cch ly d liu ->Next

60

Bc 2: chn

Bc 6: Co th Kim tra th d liu ly c->Finish

6.5.4. Thit k giao din cho cc thnh phn trong DetailsView


Bc 1: nhp chut

Tin hnh thit k cc Fields:

61

Bc 2: chn

<asp:DetailsView ID="DetailsView1" runat="server" AllowPaging="True"


AutoGenerateRows="False" DataKeyNames="ten"
DataSourceID="AccessDataSource1" Height="50px"
Width="250px">
<Fields>
<asp:BoundField DataField="ten" HeaderText="T&#234;n"
ReadOnly="True"
SortExpression="ten" />
<asp:BoundField DataField="matkhau" HeaderText="Mt khu"
SortExpression="matkhau" />
<asp:BoundField DataField="email" HeaderText="Email"
SortExpression="email" />
<asp:BoundField DataField="sodangky" HeaderText="S ng k&#253;"
SortExpression="sodangky" />
</Fields>
</asp:DetailsView>
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/db1.mdb" SelectCommand="SELECT * FROM
[ThanhVien]">
</asp:AccessDataSource>

Kt qu:

62

63

Chng 7: Khc
7.1. IIS

7.1.1. Hng dn ci t IIS cho windows 2000, XP


1) Vo Control Panel, Start -> Settings -> Control Panel. Khi vo c Control Panel
click vo Add/Remove Programs

2) Khi vo c Add/Remove Program, bn chn Add/Remove Windows Components.

3) nh du Internet Information Services (IIS). Ri Click Next.

64

4) Cho a CD Windows 2000 hay Windows XP (ty theo h iu hnh ca bn) vo ri


nhn OK.

5) Windows s bt u ci t IIS components.

65

6) Ci t xong!

7.1.2. Kim tra trnh ch IIS


kim tra trnh ch khi ng v hot ng tt, co th g a ch cc b ngay trn trnh
duyt nh sau: http://localhost/ hoc http://172.0.0.1/ Kt qu trnh duyt s hin th trang
Web mc nh (default.asp) ca IIS cng vi trang hng dn s dng ASP.
Trang ch mc nh ca IIS

66

Trang ti liu hng dn ca IIS v lp trnh ASP

67

7.1.3. Trang Web u tay.


1) V d v trang HTML. Dng notepad lp ra mt tp tin index.htm, ri lu xung th
mc gc Home directory (C:\Inetpub\wwwrooot)
<HTML>
<HEAD>
<TITLE>Wellcome to IIS</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1><B>Wellcome to IIS !</B></H1>
</CENTER>
</BODY>
</HTML>

Th li kt qu trang HTML.
68

2) V d v trang ASP. Dng notepad lp ra mt tp tin Hello.asp, ri lu xung th mc


gc Home directory (C:\Inetpub\wwwrooot)
<HTML>
<HEAD>
<TITLE>Wellcome to ASP</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1><B>Wellcome to
ASP</B></H1>
<%
For i=1 to 5
Response.Write
"<FONT size="+CStr(i)+"> Hello
</FONT><BR>"
Next
%>
</CENTER>
</BODY>
</HTML>

Th li kt qu trang ASP.

69

7.1.4. Qun l trnh ch Web Server


1) M trnh qun l MMC
Microsoft cung cp giao din ha cho php qun l ton b ng dng Web gi l MMC
(Microsoft Management Console). hin th ca s ny co th thc hin nh sau: Menu
Start -> Programs -> Administrative Tools -> Internet Information Services.

2) Xem cc thuc tnh ca Default Web Site.

70

2.1) y l nhng thuc tnh khi qut ca Web site. y chung ta co th gn IP, vo cng
c nh cho web site bng cch vit vo IP v port. Mc nh ban u IP s co IP gn c ho
my v cng 80. Ngoi ra ta co th mc nh thi gian server dnh ra cho tng mi kt ni t
client trc khi ngt kt ni o.

2.2) Phn hiu sut co nhng c tnh sau, v tuy theo mt truy cp web site thay hiu
xut ca web site v cc ti nguyn ca my dnh cho web service, nh tng thm thi gian
s dng CPU cho web service khi nhiu ngi truy cp.

71

2.3) Phu mc nh th mc ch (Home directory) nh sau. Trong phn ny bn co th i


th mc chnh ca web site hay l thay i cc quyn s dng trn th mc o.

2.4) Phn document l xc nh mt danh sch cc trang default khi goi url ca web site.

72

3) To th mc o (Virtual Folder) cho ng dng.


Co th to cc th mc o bn di ng dng Default Web Site. to th mc o cha ng
dng, ta thc hin cc bc sau:
3.1) Nhn phm phi vo Default Web Site, chn New / Virtual Directory t menu tt.
3.2) MMC s hin th trnh tr gip Wizard t tn b danh (Alias) cho th mc o chng hn
AdvWords, sau o chn Next n bc k tip.
3.3) MMC hin th hp thoi chn ng dn vt l trn my ch tng ng vi th mc
o AdvWords,
3.4) Nhn Next n mn hnh t cu hnh bo v v c quyn cho th mc o,
Nhn Next v Finish xc nhn. IIS s to mt th mc o AdvWorks bn di Default
Web Site. truy xut cc trang thuc th mc o ny co th s dng a ch Web URL nh
sau: http://localhost/AdvWorks/Hello.asp

7.2. Javascript trong ASP.NET


V d minh ho
Bi 1: Nhp vo tn ngi s dng. Xut thng bo cho

73

Bai1_XuatTBChao.htm
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script language="javascript">
var sTen = new String();
sTen = prompt("Vui lng nhp tn: ");
alert ("Xin cho bn " + sTen);
</script>
</head>
<body>
</body>
</html>

Bi 2: Nhp vo 2 s nguyn a v b. Tnh tng 2 s nguyn a v b di 2 dng:


a) Nhp t Script Prompt
b) Nhp t HTML Control
a) Nhp t Script Prompt
74

Bai2a_TinhTong2SoNguyen.htm
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script language="javascript">
75

var a, b = new Number();


var S = new Number();
var Chuoi = new String();
Chuoi = prompt("Nhp a: ");
a = parseInt(Chuoi);
Chuoi = prompt ("Nhp b: ");
b = parseInt (Chuoi);
S = a + b;
alert ("Tng l: " + S);
</script>
</head>
<body>
</body>
</html>

b) Nhp t HTML Control

76

Bai2b_TinhTong2SoNguyen.htm
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script language="javascript">
function TinhTong()
{
var a, b = new Number();
var S = new Number();
var Chuoi = new String();
Chuoi = document.getElementById("txt_a").value;
a = parseInt(Chuoi);
Chuoi = document.getElementById("txt_b").value;
b = parseInt(Chuoi);
S = a + b;
//Xut kt qu
var newChild;
var oldChild;
Chuoi = "Tng: " + S;
newChild = document.createTextNode(Chuoi);
oldChild=document.getElementById("KetQua").childNodes[0];
document.getElementById("KetQua").replaceChild(newChild,oldChild);
}
</script>
</head>
<body>
<h1>Tng 2 s nguyn</h1>
a: <input id="txt_a" type="text" /> <br />
b: <input id="txt_b" type="text" /> <br />
<input id="Button1" type="button" value="Tnh tng"
onclick="TinhTong()"/>
<div id="KetQua">&nbsp;</div>
</body>
</html>

77

Bi 3: Nhp vo 2 cnh gc vung a v b ca tam gic vung. Tnh chiu di cnh


huyn ca tam gic.

Kt qu

78

Bai3_TinhCanhHuyenTGVuong.htm
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
</head>
<body>
<script language="javascript">
var a, b = new Number();
var c = new Number();
var Chuoi = new String();
Chuoi = prompt("Nhp cnh a: ");
a = parseInt(Chuoi);
Chuoi = prompt ("Nhp cnh b: ");
b = parseInt (Chuoi);
c = Math.sqrt(a*a+b*b);
alert ("Cnh huyn: " + c);
</script>
</body>
</html>

79

Bi 4: Tnh tng dy s nguyn a c n phn t.

80

Bai4_TinhTongDaySoNguyen.htm
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script language="javascript">
var a = new Array();
var n = new Number();
var S = new Number();
var Chuoi = new String();
//Nhp
Chuoi = prompt("Nhp dy cc s nguyn: ");
a = Chuoi.split(",");
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
n = 4;
n = a.length;
for (var i=0; i < n; i++)
a[i] = parseInt(a[i]);
S = 0;
for (var i=0; i < n; i++)
S = S + a[i];
//Xut kt qu
alert ("Tng: " + S);
</script>
</head>
<body>
</body>
</html>

81

Bi 5: Tnh tng 2 phn s A v B

Bai5_Tong2PhanSo.htm
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script language="javascript">
function PhanSo()
{
this.TuSo = new Number();
this.MauSo = new Number();
}
82

function NhapPhanSo(A,B)
{
var Chuoi = new String();
//Phn s A
Chuoi = document.getElementById("txt_TuSoA").value;
A.TuSo = parseInt(Chuoi);
Chuoi = document.getElementById("txt_MauSoA").value;
A.MauSo = parseInt(Chuoi);
//Phn s B
Chuoi = document.getElementById("txt_TuSoB").value;
B.TuSo = parseInt(Chuoi);
Chuoi = document.getElementById("txt_MauSoB").value;
B.MauSo = parseInt(Chuoi);
}
function TinhTong(A,B)
{
var Kq = new PhanSo();
Kq.TuSo = A.TuSo * B.MauSo + B.TuSo * A.MauSo;
Kq.MauSo = A.MauSo * B.MauSo;
return Kq;
}
function XuatPhanSo(A)
{
var Chuoi;
Chuoi = A.TuSo + "/" + A.MauSo;
alert(Chuoi);
}
function XuLy ()
{
var A = new PhanSo();
var B = new PhanSo();
var S = new PhanSo();
NhapPhanSo(A,B);
S= TinhTong(A,B);
XuatPhanSo(S);
}
</script>
</head>
<body>
<h1>Tng 2 Phn S</h1>
Phn s A: T s: <input id="txt_TuSoA" type="text" /> Mu s: <input
id="txt_MauSoA" type="text" /> <br />
Phn s B: T s: <input id="txt_TuSoB" type="text" /> Mu s: <input
id="txt_MauSoB" type="text" /> <br />
<input id="Button1" type="button" value="Tnh tng" onclick="XuLy()"/>
</body>
</html>

83

7.3. AJAX

7.3.1. Gii thiu


7.3.1.1 Tng quan v m hnh ng dng Web

Kin trc ca ng dng Web

Mt s c im:
* X l h khch (Client):
+ u im:
- Giao din p
- Kh nng tng tc cao
- Gim ti cho Server
- Tc x l nhanh
+ Hn ch:
- Kho pht trin
- i hi phn mm h tr
- Kh nng tng thch vi trnh duyt khng cao.
* X l h phc v (Server)
84

+ u im:
- Pht trin n gin
- Trin khai v bo tr d dng
- Chia s c d liu
+ Khuyt im
- Giao din ngi dng th s
- Tnh tng tc km

7.3.1.2 Gii thiu v AJAX


Vit tt ca t Asynchronous Javascript And XML
l mt nhom cc cng ngh pht trin web c s dng to cc ng dng web ng hay cc ng
dng RIA (rich Internet application)

M hnh truyn thng tng tc gia Client-Server

M hnh AJAX trong tng tc gia Client-Server


V d:

85

7.3.2. K thut lp trnh AJAX


7.3.2.1. X l h khch (Client)
7.3.2.1.1. i tng XMLHTTPRequest
i tng XMLHttpRequest trao i d liu mt cch khng ng b vi h phc v
(Server).

86

M hnh hot ng ca AJAX


Khi to i tng nhn/gi cc yu cu d liu xml thuc i tng XMLHTTPRequest :
var xmlhttp

Nu s dng trnh duyt Web IE5, IE6:


var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

Nu s dng trnh duyt Web IE7 tr ln, Firefox, Chrome, Opera, Safari
var xmlhttp = new XMLHTTPRequest();

7.3.2.1.2. Cc phng thc v thuc tnh ca i tng XMLHTTPRequest


Thuc tnh

M t

onreadystatechange

Xc nh s kin (hm) s c gi khi thuc tnh readState ca i tng


thay i

readyState

Cho bit trng thi ca i tng request:


0 = Cha khi to (uninitialized)
1 = ang ti d liu
2 = ti xong d liu
3 = ang tng tc
4 = hon tt

responseText

D liu c tr v bi server di dng chui text

responseXML

D liu c tr v bi server di dng i tng d liu (XML, )

87

status

M trng thi HTTP c tr v bi server

statusText

Chui trng thi c tr v bi server

Phng thc

M t

abort()

Dng gi yu cu n server

getAllResponseHeaders()

Tr v tt c cc tiu (headers) di dng chui

getresponseHeader(x)

Tr v gi tr ca tiu (header) x di dng chui

open('method','URL','a')

Xc nh phng thc ca HTTP (GET hoc POST), URL l ng


dn gi yu cu n server (bt ng b) (nu a=true: mc nh)

send(content)

Data gi yu cu vi tu chn POST

setRequestHeader('x','y')

t tham s v gi tr x=y v gn no vo tiu v s c gi


cng vi yu cu.

7.3.2.2. X l h phc v (Server)


Trong k thut AJAX, h phc v (server) giao din hin th thng thng khng co cc th
<html></html> m ch co chui XML

ASP.NET
using
using
using
using
using
using
using
using
using
using

System;
System.Data;
System.Configuration;
System.Collections;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Web.UI.HtmlControls;

public partial class BaiGiang_ServerSide : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
string sXML = "<?xml version='1.0' encoding='UTF-8'?>";
sXML = sXML + "<Goc ";
sXML = sXML + "ThongBao='Xin cho n vi AJAX'";
88

sXML = sXML + "/>";


Response.ContentType = "text/xml";
Response.Write(sXML);
}
}

PHP
<?php
header('Content-Type: text/xml');
echo "<?xml version='1.0' encoding='UTF-8'?><Goc ThongBao='Xin cho n
vi AJAX'/>";
?>

7.3.3. V d
V d 1: Nhp vo tn ngi s dng. Xut thng bo cho

M ngun:
* X l h khch:
Bai1_XuatTBChao.htm
<!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>
<title>Untitled Page</title>
<script language="javascript">
var xmlhttp
function XuatThongBao()
{
var sTen = new String();
sTen = document.getElementById("txt_Ten").value;
89

var ThamSo = "Ten=" + sTen;


var URL = "./XuatThongBaoChao.aspx" + "?" + ThamSo;
xmlhttp = GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support AJAX!");
}
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",URL,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
var sThongBao = new String();
var xmlDoc=xmlhttp.responseXML.documentElement;
sThongBao = xmlDoc.getAttribute("ThongBao");
alert(sThongBao);
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// dng cho IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// dng cho IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
</head>
<body>
Nhp tn: <input id="txt_Ten" type="text" /> <br />
<input id="Button1" type="button" value="Xut Thng Bo"
onclick="XuatThongBao()"/>
<div id="KetQua">&nbsp;</div>
</body>
</html>

* X l h phc v:
90

XuatThongBaoChao.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="XuatThongBaoChao.aspx.cs" Inherits="clsXuatThongBaoChao" %>

XuatThongBaoChao.aspx.cs
using
using
using
using
using
using
using
using
using
using

System;
System.Data;
System.Configuration;
System.Collections;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Web.UI.HtmlControls;

public partial class clsXuatThongBaoChao : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
string sTen;
string sThongBao;
sTen = Request["Ten"];
sThongBao = "Xin cho bn " + sTen;
//to chui
string sXML
sXML = sXML
sXML = sXML
sXML = sXML

XML
= "<?xml version='1.0' encoding='UTF-8'?>";
+ "<Goc ";
+ "ThongBao='" + sThongBao + "'";
+ "/>";

Response.ContentType = "text/xml";
Response.Write(sXML);
}
}

V d 2: Nhp vo 2 s nguyn a v b. Tnh tng 2 s nguyn a v b

91

M ngun:
* X l h khch:
Bai2_TinhTong2SoNguyen.htm
<!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>
<title>Untitled Page</title>
<script language="javascript">
var xmlhttp
function
{
var
var
var

TinhTong()
a, b = new Number();
S = new Number();
Chuoi = new String();

Chuoi = document.getElementById("txt_a").value;
a = parseInt(Chuoi);
Chuoi = document.getElementById("txt_b").value;
b = parseInt(Chuoi);
//gui ket qua ve server
var ThamSo = "a=" + a + "&b=" + b;
var URL = "./TinhTong2SoNguyen.aspx" + "?" + ThamSo;
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",URL,true);
xmlhttp.send(null);
92

}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
var xmlDoc=xmlhttp.responseXML.documentElement;
S = xmlDoc.getAttribute("Tong");
Chuoi = "Tng: " + S;
var newChild = document.createTextNode(Chuoi);
var oldChild =
document.getElementById("KetQua").childNodes[0];
document.getElementById("KetQua").replaceChild(newChild,
oldChild);
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// dng cho IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// dng cho IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
</head>
<body>
<h1>Tng 2 s nguyn</h1>
a: <input id="txt_a" type="text" /> <br />
b: <input id="txt_b" type="text" /> <br />
<input id="Button1" type="button" value="Tnh tng"
onclick="TinhTong()"/>
<div id="KetQua">&nbsp;</div>
</body>
</html>

93

* X l h phc v
TinhTong2SoNguyen.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="TinhTong2SoNguyen.aspx.cs" Inherits="clsTinhTong2SoNguyen" %>

TinhTong2SoNguyen.aspx.cs
using
using
using
using
using
using
using
using
using
using

System;
System.Data;
System.Configuration;
System.Collections;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Web.UI.HtmlControls;

public partial class clsTinhTong2SoNguyen : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
int a;
int b;
int S;
string chuoi;
chuoi = Request["a"];
a = int.Parse(chuoi);
chuoi = Request["b"];
b = int.Parse(chuoi);
S = a + b;
//to chui
string sXML
sXML = sXML
sXML = sXML
sXML = sXML

XML
= "<?xml version='1.0' encoding='UTF-8'?>";
+ "<Goc ";
+ "Tong='" + S.ToString() + "'";
+ "/>";

Response.ContentType = "text/xml";
Response.Write(sXML);
}
}

7.4. Web Service

7.4.1. Gii thiu


Web service l mt h thng phn mm c thit k h tr kh nng tng tc gia cc
ng dng trn cc my tnh khc nhau thng qua mng Internet, giao din chung v s gn kt ca no
94

c m t bng XML. Web service cung cp cc phng thc chun trong vic gi v truy cp n
cc h thng ong goi v h thng k tha.
Cc phn mm c vit bi nhng ngn ng lp trnh khc nhau v chy trn nhng nn
tng khc nhau co th s dng dch v web (web service) chuyn i d liu thng qua mng
Internet theo cch giao tip tng t bn trong mt my tnh. No bao gm cc module c lp cho
hot ng ca khch hng v doanh nghip v bn thn no c thc thi trn server.
Web service gip gim chi ph v phc tp trong tch hp v pht trin h thng.

7.4.2. c im
Web service cho php client v server tng tc c vi nhau ngay c tro ng nhng mi
trng khc nhau.
V d: t Web server cho ng dng trn mt my ch chy h iu hnh Linux trong khi
ngi dng s dng my tnh chy h iu hnh Windows, ng dng vn co th chy v x l bnh
thng m khng cn thm yu cu c bit tng thch gia hai h iu hnh ny.
Phn ln k thut ca web service c xy dng da trn m ngun m v c pht trin t
cc chun c cng nhn chng hn nh XML.
Mt web service bao gm co nhiu module v co th cng b ln mng Internet.

7.4.3. Kin trc ca Web Services


Web service gm co 3 chun chnh: SOAP (Simple Object Access Protocol), WSDL (Web
Service Description Language) v UDDI (Universal Description, Discovery, and Integration). Trong
o UDDI c s dng ng k v khm ph dch v Web c miu t c th trong WSDL.
Giao tc UDDI s dng SOAP lin lc vi UDDI server. Sau o cc ng dng SOAP yu cu mt
dch v Web. Cc thng ip SOAP c gi i bi HTTP v TCP/IP.

7.4.4. Cc thnh phn ca Web Service


a) XML (eXtensible Markup Language)
XML l mt chun m do W3C a ra cho cch thc m t d liu, no c s dng nh
ngha cc thnh phn d liu trn trang web v cho nhng ti liu B2B. V hnh thc, XML hon
ton co cu trc th ging nh ngn ng HTML nhng HTML nh ngha thnh phn c hin th
th XML li nh ngha nhng thnh phn d liu cha bn trong. Vi XML, cc th co th c lp
trnh vin t to ra trn mi trang web v c chn l nh dng thng ip chun bi tnh ph bin
v hiu qu m ngun m.
Web service l s kt hp ca nhiu thnh phn khc nhau nn no s dng cc tnh nng v
c trng ca cc thnh phn o giao tip. XML l kin trc nn tng cho vic xy dng mt dch
v Web, tt c d liu s c chuyn sang nh dng th XML.
b) WSDL (Web Service Description Language)
WSDL nh ngha cch m t dch v Web theo c php tng qut ca XML, bao gm cc
thng tin:
+ Tn dch v
+ Giao thc v kiu m hoa s c s dng khi gi cc hm ca web service.
+ Loi thng tin: thao tc, tham s, nhng kiu d liu
95

WSDL thng c s dng kt hp vi XML schema v SOAP cung cp web service


qua Internet. Mt client khi kt ni ti web service co th c WSDL xc nh nhng hm
(phng thc) sn co trn server. Sau o, client co th s dng SOAP ly ra cc chc nng co
trong WSDL.
c) UDDI (Universal Description, Discovery, and Integration)
co th s dng cc dch v, trc tin client phi tm dch v, ghi nhn thng tin v cch
s dng v bit c i tng no cung cp dch v. UDDI nh ngha mt s thnh phn cho bit
cc thng tin ny, cho php cc client truy tm v nhn nhng thng tin c yu cu khi s dng
dch v Web.
Cu trc UDDI :
+ White pages (Trang trng): cha thng tin lin h v cc nh dng chnh yu ca web
service, chng hn tn giao dch, a ch, thng tin nhn dng Nhng thng tin ny cho
php cc i tng khc xc nh c dch v.
+ Yellow pages (Trang vng): cha thng tin m t web service theo nhng loi khc nhau.
Nhng thng tin ny cho php cc i tng thy c web service theo tng loi vi no.
+ Green pages (Trang xanh): cha thng tin k thut m t cc hnh vi v cc chc nng ca
web service.
+ tModel (Loi dch v): cha cc thng tin v loi dch v c s dng.
Nhng thng tin v web service c s dng v cng b ln mng s dng giao thc ny.
No s kch hot cc ng dng tm kim thng tin ca web service khc nhm xc nh xem dch
v no s cn n no.
d) SOAP (Simple Object Access Protocol)
SOAP l mt giao thc giao tip co cu trc nh XML. No c xem l cu trc xng sng
ca cc ng dng phn tn c xy dng t nhiu ngn ng v cc h iu hnh khc nhau. SOAP
l giao thc thay i cc thng ip da trn XML qua mng my tnh, thng thng s dng giao
thc HTTP.
Mt client s gi thng ip yu cu ti server v ngay lp tc server s gi nhng thng ip
tr li ti client. C SMTP v HTTP u l nhng giao thc lp ng dng ca SOAP nhng HTTP
c s dng v chp nhn rng ri hn bi ngy nay no co th lm vic rt tt vi c s h tng
Internet.

7.4.5. V d xy dng web service n gin


a) Xy dng 1 ng dng web service cho php:
- Xut thng bo cho
- Tnh tng 2 s nguyn a v b
b) Client truy xut vo ng dng web service trn c vit di d ng:
- Windows Application
- ASP.NET Web Application
- HTML page (s dng JavaScript gi)
Thc hin:
a) Xy dng ng dng Web Service
Trong Visual Studio 2005, vo menu File -> New -> Web site
Chn ASP.NET Web Service

96

Xy dng 2 lp Service gm 2 phng thc Web:


public string XuatThongBaoChao()
public int TinhTong(int a, int b)

97

- Bin dch v thc thi (Nhp phm F5)

98

b) Xy dng ng dng Client truy xut ng dng Web Service


* Windows Application

99

Thm tham chiu n Web service

100

Nhp a ch URL ca Web Service, sau o nhp tn vo Web reference name v click vo Add
Reference

101

Xy dng m ngun:
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;

namespace test_WS
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_XuatTBChao_Click(object sender, EventArgs e)
{
MyWebService.Service ws = new MyWebService.Service();
string sThongBao;
sThongBao = ws.XuatThongBaoChao();
MessageBox.Show(sThongBao);
}
private void btn_TinhTong_Click(object sender, EventArgs e)
{
MyWebService.Service ws = new MyWebService.Service();
int a = int.Parse(txt_a.Text);
int b = int.Parse(txt_b.Text);
int s = ws.TinhTong(a, b);
MessageBox.Show(s.ToString());
}
}
}

Kt qu thc hin:

102

* ASP.NET Web Application


Thc hin tng t nh Windows Application

* HTML page

103

M ngun: test_WS.htm
<html >
<head>
<title>Vi du web service</title>
<script language="JavaScript">
function InitializeService()
{
service.useService("http://localhost:61076/ViDu_WebService/Service.asmx?ws
dl","Service");
}
function Check()
{
var a = document.getElementById("txt_a").value;
var b = document.getElementById("txt_b").value;
service.Service.callService("TinhTong", a, b);
}
function ShowResult()
{
var kq;
kq = event.result.value;
alert(kq);
}
</script>
</head>
<body onload="InitializeService()" >

104

<div id="service" style="behavior:url(webservice.htc)"


onresult="ShowResult()">
</div>
<form name="DemoForm">
a:<input type="text" id="txt_a" size="20"> </br>
b:<input type="text" id="txt_b" size="20"> </br>
<button onclick="Check()">Tinh Tong</button><br>
</form>
</body>
</html>

Lu : tp tin webservice.htc c t cng th mc vi tp tin test_WS.htm


webservice.htc gm h thng cc hm c vit bng Javascript c dng tng tc vi
cc ng dng Web service

105

You might also like