You are on page 1of 502

MC LC

Chng 1. Lp trnh Web & ASP.NET ................................................................................ 1 1.1. Gii thiu v ng dng Web ........................................................................................ 1 1.2. Gii thiu v ASP v ASP.NET ................................................................................... 4 1.3. Web Server IIS ........................................................................................................... 10 1.4. To ng dng Web vi ASP.NET .............................................................................. 13 1.5. Kho st giao din Visual Studio .NET 2008 ............................................................ 16 1.6. Bi thc hnh chng 1.............................................................................................. 19 Chng 2. Tm hiu v s dng cc Server Controls ........................................................ 21 2.1. Cu trc trang ASP.NET ............................................................................................ 21 2.2. Bin c trang ASP.NET ........................................................................................ 26 2.3. Gii thiu ASP.NET Server Controls ........................................................................ 28 2.4. HTML Server Controls .............................................................................................. 29 2.5. ASP.NET Server Controls .......................................................................................... 52 2.6. S kin PageLoad v thuc tnh IsPostBack .............................................................. 79 2.7. Thuc tnh AutoPostBack ca mt s Web Server Controls ..................................... 83 2.8. Bi thc hnh chng 2.............................................................................................. 88 Chng 3. Master Page Web Navigation ......................................................................... 94 3.1. Master Page ................................................................................................................ 94 3.2. Web Navigation ........................................................................................................ 104 3.3. Web User Control ..................................................................................................... 113 3.4. i tng Request, Response v Server .................................................................. 122 3.5. Bi thc hnh chng 3............................................................................................ 131 Chng 4. Qun l trng thi ............................................................................................ 137 4.1. Vn trng thi ...................................................................................................... 137 4.2. Xem trng thi (View State) ..................................................................................... 138 4.3. Chuyn thng tin gia cc trang............................................................................... 140 4.4. i tng Cookies ................................................................................................... 145 4.5. i tng Session .................................................................................................... 148 4.6. i tng Application .............................................................................................. 150 4.7. Tp tin Global.asax................................................................................................... 153 4.8. Tp tin Web.config ................................................................................................... 154 4.9. Bi tp chng 4 ...................................................................................................... 157 Chng 5. S dng cc Validation Controls .................................................................... 160 5.1. RequiredFieldValidator ............................................................................................ 161 5.2. iu khin RangeValidator ...................................................................................... 164 5.3. iu khin CompareValidator.................................................................................. 166 5.4. iu khin RegularExpressionValidator .................................................................. 169 5.5. iu khin Custom Validator ................................................................................... 172 5.6. iu khin ValidationSummary ............................................................................... 174 5.7. Bi thc hnh chng 5............................................................................................ 179 Chng 6. Cc i tng d liu (Rich Controls Login .............................................. 183 6.1. iu khin hin th cc trang khc nhau MultiView. .............................................. 183 6.2. iu khin Wizard.................................................................................................... 190 6.3. Nhm iu khin Login ........................................................................................... 197 6.4. Bi tp chng 6 ...................................................................................................... 203 Chng 7. Gii thiu ADO.NET ........................................................................................ 216 7.1. Kin trc ADO.NET................................................................................................. 216

7.2. Tm hiu trnh cung cp d liu ca ADO.NET ...................................................... 217 7.3. Cc namespace ca ADO.NET ................................................................................ 219 7.4. Tm hiu c ch kt ni ca ADO.NET qua Connected Layer ................................ 223 7.6. Disconnected Layer .................................................................................................. 247 7.7. i tng d liu SqlDataSource ............................................................................ 256 7.8. Bi tp chng 7 ...................................................................................................... 264 Chng 8. Tm hiu v ng dng c ch Data Binding ................................................... 268 8.1. Cc dng Data Binding. ............................................................................................ 268 8.2. Bi tp chng 8 ...................................................................................................... 274 Chng 9. Cc i tng d liu (Data Controls) ........................................................... 279 9.1. i tng d liu GridView. ................................................................................... 279 9.2. i tng d liu DetailsView ................................................................................ 299 9.3. i tng d liu FormView ................................................................................... 302 9.4. i tng d liu DataList....................................................................................... 304 9.5. i tng d liu Repeater ...................................................................................... 308 9.6. Bi thc hnh chng 9............................................................................................ 310 Chng 10. Bo mt cc ng dng Web ........................................................................... 312 10.1. Gii Thiu v Bo Mt Trong ASP.Net. ................................................................. 312 10.2. Th d minh ha ...................................................................................................... 313 Chng 11. Gii thiu AJAX ............................................................................................ 319 11.1. Gii thiu Ajax...................................................................................................... 319 11.2. Ajax lm vic nh th no?................................................................................... 319 11.3. ASP.Net Ajax Server Control ............................................................................... 328 11.4. Gii thiu Ajax Toolkit 3.5 ................................................................................... 331 11.5. Tm hiu mt s iu khin trong Ajax Toolkit 3.5.............................................. 336 11.6. Bi thc hnh chng 11 ...................................................................................... 382 Chng 12. Lp trinh LINQ .............................................................................................. 396 12.1. Gii Thiu LINQ. ................................................................................................. 396 12.2. Cc Khi Nim C Bn ........................................................................................ 398 12.3. LINQ to Objects .................................................................................................... 404 12.4. LINQ to DataSet ................................................................................................... 405 12.5. LINQ to SQL ........................................................................................................ 408 Chng 13. Lp trnh Web Services ................................................................................ 415 13.1. Gii thiu Web services. ....................................................................................... 415 13.2. Kin trc v cc thnh phn Web services ........................................................... 416 13.3. Xy Dng ng Dng Web Service ...................................................................... 420 Chng 14. Xy dng Website bn hng ......................................................................... 427 Chng 15. Thit k Website bn hng Mc d liu .................................................... 436 Chng 16. Thit k Website bn hng Mc x l........................................................ 451 Chng 17. Thit k Website bn hng Mc trnh din ............................................... 474

Chng 1:

Lp Trnh Web & ASP.Net

Kt thc chng ny cc bn c th :
Trnh by c khi nim ng dng thng mi in t M t c cc khi nim c bn v Web,kin trc Client-Server 2 lp v 3 lp. M t c cc ngn ng lp trnh Web: HTML, DHTML, VBScript,JavaScript. Trnh by v ci t c Web Server IIS. Trnh by c cc c im ca ASP v ASP.Net S dng c Visual Studio .Net 2008 to ng dng Web 1.1 Gii Thiu v ng Dng Web Cng vi s pht trin mnh m v cng ngh thng tin, c bit l s pht trin h thng mng intranet, internet... Trong cc lnh vc ngy nay nh : thng mi, y t, gio dc..., nhu cu trao i thng tin thc s l cn thit, gip cho cng vic c trin khai nhanh , chnh xc, d dng v tit kim chi ph, thng tin c cp nht kp thi. Do vn t ra l chng ta cn phi c mt ng dng cho php trao i thng tin mi lc, mi ni, d s dng, thng qua mng. ng dng Web p ng c cc yu cu t ra v sau y l cc l do ti sao chng ta phi s dng Web : D dng trao i v chia s thng tin thng tin qua mng . S dng giao din ha gip cho ngi dng d s dng . H tr v multimedia nh : hnh nh , m thanh, phim nh, H tr nhiu chng trnh(web-browser) truy cp Web. H tr truy cp web trn cc thit b i ng: PocketPC, SmartPhone, H tr nhiu ngn ng pht trin Web: ASP, ASP.NET, JSP, PHP

Web client (Browser) My khch(Client) s s dng chng trnh truy cp n cc trang web gi l trnh duyt web hay browser. Hin rt nay c nhiu trnh duyt web nh : Internet Explorer , Nescape, Mozila FireFox,.. Web server Cc my ch(Server) cha cc ng dng Web, sn sng truy xut cc trang web hay cc ti liu v gi v cho client khi nhn c yu cu t pha Client. Hin nay c rt nhiu Web server v chy trn nhiu h thng nh : Apache, Microsoft,Sun, Giao thc HTTP Qu trnh giao tip gia client v server c thc hin thng qua giao thc chun HTTP(HyperText Transfer Protocol).Hnh minh ha sau m t vic truy cp ng dng Web.

Lu hnh ni b

Trang 1

Hnh 1.1: Minh ha truy cp ng dng Web Web c pht trin trn m hnh client-server Giao thc HTTP: Qu trnh giao tip gia client v server c thc hin thng qua giao thc chun HTTP(HyperText Transfer Protocol). M hnh gm hai thnh phn chnh l: my khch(client) v my phc v(server). My phc v(server) s cha cc ng dng Web v cc ng dng Web ny s c qun l tp trung bi trnh qun l gi l Web Server (IIS,). Cc my khch(client) truy cp n ng dng web s dng trnh duyt web(browser). Client s dng giao thc HTTP Request gi yu cu(trang web) ln Server, Server x l v s dng giao thc HTTP Response gi kt qu v cho Client.

Ngn ng HTML Ngn ng chun to mt trang Web. HTML cho php ngi vit c th phn chia v trnh by thng tin trn mt trang tin. HTML n gin, d hc. HTML n gin l tp tin c phn m rng .htm(.html), s dng cc th(tag): kiu vn bn, danh sch, cc lin kt(hyperlinks) Chng ta c th dng FrontPage, DreamWeaver thit k cc trang HTML, Ngn ng nh du HTML s dng cc k hiu quy nh sn (c gi l tag) trnh by ni dung vn bn.

Hnh 1.2 Trang siu vn bn HTML Lu hnh ni b Trang 2

Th d 1.1: Ni dung trang web Sample.htm <Html> <Head> <Title>ASP.Net</Title> </Head> <Body> <P align="center"> <FONT size="6"> Cho cc bn n vi ASP.Net 3.5!!! </FONT> </P> </Body> </Html> Client Scripting v Server Scripting Cc ngn ng dng vit m cho trang web. Mt trang web c x l Server v tr kt qu v cho Client. Do cc ngn ng vit m cho trang web c chia thanh hai dng:

ClientScript: c x l ti trnh duyt (Browser) trn my Client. Cc ngn ng dng vit l :VBScript, JavaScript, DHTML o JavaScript l ngn ng ph bin s dng nhiu nht hin nay. JavaScript c dng kim tra vic nhp liu, kim tra trnh duyt,

o DTHML:l s kt hp ca HTML,Style Sheet(CSS) v JavaScript nhm lm cho trang web d tng tc, iu khin v gim bt vic x l pha Server. o VBScript l ngn ng script ca Microsoft. Chc nng ca VBScript cng ging nh JavaScript.

Server Scripting: c x l ti Web server trn my Server. Cc ngn ng dng

vit l :ASP,ASP.NET,PHP,JSP, Trong gio trnh ny chng ta s kho st ngn ng ASP v ASP.NET. Cc m hnh ng dng

M hnh ng dng 2 lp

Hnh 1.3 M hnh 2 lp (Two Tier) y l mt dng m hnh n gin, kh ph bin ca mt ng dng phn tn. Trong m hnh ny, vic x l d liu c thc hin trn Database Server, vic nhn v hin th d Lu hnh ni b Trang 3

liu c thc hin Client. u im D liu tp trung -> m bo d liu c nht qun. D liu c chia s cho nhiu ngi dng. Khuyt im Cc x l tra cu v cp nht d liu c thc hin Database Server, vic nhn kt quv hin th phi c thc hin Client -> Kh khn trong vn bo tr v nng cp. Khi lng d liu truyn trn mng ln -> chim dng ng truyn, thm gnh nng choDatabase Server.

M hnh ng dng 3 lp

M hnh 2 lp phn no p ng c cc yu cu khc khe ca mt ng dng phn tn, tuy nhin, khi khi lng d liu ln, ng dng i hi nhiu x l phc tp, s ngi dng tng, m hnh 2 lp khng th p ng c. M hnh 3 lp s dng thm Application Server gi nhim v tng tc gia Client v Database server, gim bt cc x l trn Database server, tp trung cc x l nhn v hin th d liu ti Application server.

Hnh 1.4 M hnh 3 lp (Three Tier) u im H tr nhiu ngi dng Gim bt x l cho Client -> Khng yu cu my tnh Client c cu hnh nh. X l nhn v hin th d liu tp trung ti Application Server ->d qun l, bo tr v nng cp. X l truy cp d liu tp trung ti Database Server. Khuyt im Phi s dng thm mt Application Server -> Tng chi ph. 1.2 Gii Thiu v ASP & ASP.NET 1.2.1 Gii Thiu v ASP Lu hnh ni b Trang 4

Active Server Page (ASP) do Microsoft pht trin l mi trng lp trnh pha server(server side scripting) h tr mnh trong vic xy dng cc ng dng thng mi in t (cc trang Web ng). Cc ng dng ASP rt d vit v d sa i, ng thi tch hp cc cng ngh sn c ca Microsoft nh : COM, T khong cui thp nin 90, ASP (Active Server Page) c nhiu lp trnh vin la chn xy dng v pht trin ng dng web ng trn my ch s dng h iu hnh Windows. ASP th hin c nhng u im ca mnh vi m hnh lp trnh th tc n gin, s dng hiu qu cc i tng COM: ADO (ActiveX Data Object) - x l d liu, FSO (File System Object) - lm vic vi h thng tp tin, ng thi, ASP cng h tr nhiu ngn ng: VBScript, JavaScript. Chnh nhng u im , ASP c yu thch trong mt thi gian di. Mt ng dng ASP c trin khai trn Web Server l IIS( Internet Information Service) c sn trong mi trng Windows. c th trin khai ng dng ASP trn cc mi trng khc ta phi ci t cc th vin h tr ASP. c im ca trang ASP L mt tp tin vn bn (text file) c phn m rng .asp. Phn m rng ny s gip Web server yu cu trnh x l trang asp(ASP engine) trc khi tr v cho trnh duyt. Ngn ng script thng dng nht vit m ca ASP l VBScript. Ngoi ra ta cng c th vit m bng cc ngn ng khc nh: JavaScript, Perl, Python,nu trn Web server c ci t cc b x l ngn ng ny. Cc on m vit trong trang ASP s c cc b x l ngn ng trn Web server x l tun t t trn xung di. Kt qu ca vic x l ny l tr v trang m HTML cho web server v web server s gi trang HTML ny v cho trnh duyt(Browser), do ti trnh duyt khng th thy c cc on m chng trnh vit trong trang ASP. Mt trang ASP gm 4 phn : D liu vn bn (text) Cc th (tag) HTML. Cc on m chng trnh pha client t trong cp th <SCRIPT> v </SCRIPT>. M chng trnh ASP c t trong cp th <% v %>. Ba thnh phn u tin l cu trc ca mt trang HTML thng thng, do c th xem mt trang ASP l mt trang HTML c nhng thm phn x l vit bng m ASP(VBScript, JavaScript). Th d 1.2: Minh ha trang ASP. <HTML><BODY> <CENTER><I><FONT COLOR="HOTPINK" size = 5> <% @Language=VBScript %> <P> <B> to my website</B>. Today is <% Response.Write Date() %> Lu hnh ni b Trang 5

</FONT></I></CENTER> </BODY> </HTML> Kt qu thc thi :

Hnh 1.5: Minh ha kt qu trang Sample.asp u im Trang ASP c din dch mt cch t ng. Xy dng ng dng Web ng. X l d liu ng hiu qu. Nhc im: Ch s dng hai ngn ng kch bn phi nh kiu(non-type): VBScript v JavaScript. S dng trnh thng dch cho cc trang ASP. Cc on m lnh v giao din (HTML) trn ln vi nhau. Khng s dng li c (reuse) cc on m. Khng h tr c ch by li (Debug). 1.2.2 Gii thiu v ASP.NET Nh chng ta bit, ASP vn cn tn ng mt s kh khn nh Code ASP v HTML ln ln, iu ny lm cho qu trnh vit code kh khn, th hin v trnh by code khng trong sng, hn ch kh nng s dng li code. Bn cnh , khi trin khai ci t, do khng c bin dch trc nn d b mt source code. Thm vo , ASP khng c h tr cache, khng c bin dch trc nn phn no hn ch v mt tc thc hin. Qu trnh x l Postback kh khn, u nm 2002, Microsoft gii thiu mt k thut lp trnh Web kh mi m vi tn gi ban u l ASP+, tn chnh thc sau ny l ASP.Net. Vi ASP.Net, khng nhng khng cn i hi bn phi bit cc tag HTML, thit k web, m n cn h tr mnh lp trnh hng i tng trong qu trnh xy dng v pht trin ng dng Web. ASP.Net l k thut lp trnh v pht trin ng dng web pha Server (Server-side) da Lu hnh ni b Trang 6

trn nn tng ca Microsoft .Net Framework. Hu ht, nhng ngi mi n vi lp trnh web u bt u tm hiu nhng k thut pha Client (Client-side) nh: HTML, Java Script, CSS (Cascading Style Sheets). Khi Web browser yu cu mt trang web (trang web s dng k thut client-side), Web server tm trang web m Client yu cu, sau gi v cho Client. Client nhn kt qu tr v t Server v hin th ln mn hnh. ASP.Net s dng k thut lp trnh pha server th hon ton khc, m lnh pha server (v d: m lnh trong trang ASP) s c bin dch v thi hnh ti Web Server. Sau khi c Server c, bin dch v thi hnh, kt qu t ng c chuyn sang HTML/JavaScript/CSS v tr v cho Client. Tt c cc x l lnh ASP.Net u c thc hin ti Server v do , gi l k thut lp trnh pha server. ASP.Net c Microsoft pht trin qua nhiu phin bn t ASP.Net 1.0 , 1.1, 2.0 v gn y nht l phin bn ASP.Net 3.5 chy trn .Net Framework 3.5 s dng mi trng pht trin tch hp (IDE) Visual Studio.Net 2008 . Trong gio trnh ny chng s dng ASP.Net 3.5 Ti sao phi s dng ASP.Net ? Yu cu v xy dng cc ng dng thng mi in t ngy cng uc pht trin v nng cao. Khi ASP khng cn p ng c yu cu t ra. ASP c thit k ring bit v nm tng phi trn h iu hnh Windows v Internet Information Service, do cc cng dng ca n ht sc ri rt v gii hn. ASP.Net a ra mt phng php pht trin hon ton mi khc hn so vi ASP trc kia v p ng c cc yu cu t ra.Hnh 4.5 minh ha cc thnh phn bn trong ASP.Net 3.5

Hnh 1.6: Cc thnh phn ca ASP.Net 3.5 Cc u im ca ASP.Net ASP ch s dng VBScript v JavaScript m khng s dng c cc ngn ng mnh khc : Visual Basic, C++ Trong khi ASP.NET cho php vit nhiu ngn ng : VBScript,JavaScript, C#, Visual Basic.Net,

ASP.Net s dng phong cch lp trnh mi: Code behide. Tch code ring, giao din ring . D c, d qun l v bo tr. Lu hnh ni b Trang 7

Trong cc trang ASP chng ta phi vit m kim tra d liu nhp t ngi dng , ASP.NET h tr cc validation controls kim tra chng ta khng cn vit m,... H tr pht trin Web c truy cp trn cc thit b di ng: PocketPC, Smartphone H tr nhiu web server control . H tr thit k v xy dng MasterPage lng nhau. H tr by li (debug) JavaScript Cho php ngi dng thit lp giao din trang Web theo s thch c nhn s dng Theme, Profile, WebPart Tng cng cc tnh nng bo mt (security) H tr k thut truy cp d liu mi LINQ H tr k thut xy dng cc ng dng a phng tin SilverLight H tr k thut bt ng b ASP.Net Ajax ASP.Net h tr mnh m b th vin phong ph v a dng ca .Net Framework, lm vic vi XML, Web Service, truy cp c s d liu qua ADO.Net, ASPX v ASP c th cng hot ng trong 1 ng dng. Kin trc lp trnh ging ng dng trn Windows. H tr qun l trng thi ca cc control T ng pht sinh m HTML cho cc Server control tng ng vi tng loi Browser H tr nhiu c ch Cache. Trin khai ci t : Khng cn lock, khng cn ng k DLL, cho php nhiu hnh thc cu hnh ng dng H tr qun l ng dng mc ton cc: Global.aspx c nhiu s kin hn, qun l session trn nhiu Server, khng cn Cookies Trang ASP.Net c bin dch trc. Thay v phi c v thng dch mi khi trang web c yu cu, ASP.Net bin dch nhng trang web ng thnh nhng tp tin DLL m Server c th thi hnh nhanh chng v hiu qu. Yu t ny lm gia tng tc thc thi so vi k thut thng dch ca ASP.

Hnh 1.7 Minh ha qu trnh bin dch trang ASP.Net Th d 1.3: Minh ha trang ASP.Net hin th ngy hin hnh.

Lu hnh ni b

Trang 8

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Sample._Default" %> <!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 runat="server"> <title>ASP.Net 3.5</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lbMsg" runat="server" Text="Ngy hin hnh:"></asp:Label> </div> </form> </body> </html> Hnh 1.6: Ni dung trang Default.aspx using using using using using using using using using using using using System; System.Collections; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

namespace Sample { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lbMsg.Text = lbMsg.Text + DateTime.Now.ToString("dd/MM/yyyy"); } } Hnh 1.7: Ni dung trang Default.aspx.cs }

Lu hnh ni b

Trang 9

Hnh 1.8: Kt qu trang Default.aspx Qu trnh x l tp tin .ASPX Khi Web Server nhn c yu cu t pha client, n s tm kim tp tin c yu cu thng qua chui URL c gi v, sau , tin hnh x l theo s sau:

Hnh 1.9: Qu trnh x l tp tin .aspx 1.3 Web Server IIS Trong phn ny chng kho st v IIS (phn mm Web Server ca Microsot dnh cho Windows), ng thi hng dn bn ci t, cu hnh v kim tra Web Server trn cc h thng s dng Windows 2000, Windows XP, Windows Server 2003,Vista, Lu hnh ni b Trang 10

Internet Information Services IIS c th c s dng nh mt Web server, kt hp vi ASP xy dng cc ng dng Web tn dng cc im mnh ca Server-side Script, COM component, theo m hnh Client/Server. IIS c rt nhiu phin bn, u tin c pht hnh ri trong bn Service pack ca WinNT. Cc phin bn Windows 2000 c tch hp IIS 5.0. Windows XP tch hp IIS 5.5 Windows Vista tch hp IIS 6 Cc bc ci t Web Server trn Windows XP Professional Windows XP tch hp sn IIS nhng khng t ng ci t do , bn phi t ci IIS nu h thng c ci ri. Bc 1. Chn Control Panel | Add/Remove programs. Bc 2. Add/Remove Windows Components.

Ci t Web Server

Hnh 1.10 : Ci t IIS t a Windows XP Bc 3. nh du vo mc Internet Information Services (IIS). Bc 4. Chn nt Details chn cc mc chi tit. Bc 5. Chn cc mc cn ci t trong bn nh chn: FrontPage 2000 Server Extensions v Internet Information Services Snap-In Bc 6. Nhp nt Next (c th Windows yu cu a CD Windows XP ) ci t hon tt. Lu hnh ni b Trang 11

Bc 7: xc nh vic ci thnh cng Web Server, ta c th kim tra nh sau: M trnh duyt (Browser) : Microsoft Internet Explorer v g http://localhost/localstart.asp vo hp a ch v sau nhn Enter th trang localstart.asp mc nh s xut hin nh sau.

Hnh 1.11: Minh ha ci t IIS thnh cng Localhost l a ch ca my cc b m bn ang lm vic. Nu my ca bn ang kt ni vo mng LAN v c mt a ch IP, bn c th dng a ch ny thay cho localhost. xc nh a ch IP ca my mnh: Vo menu Start|Run v g lnh: command hoc cmd Trn mn hnh DOS, g lnh: ipconfig v xem phn IP Address Khi g //localhost, bn s thy trong thanh a ch t ng i thnh: http://localhost. HTTP l giao thc mc nh c dng trn Internet. V HTTP l mt giao thc thuc b TCP/IP, bn cn c a ch IP cc my tnh khc trong mng c th truy cp c n trang web ca bn. Sau khi ci t Web Server, mc nh trn a C:\ s c sn th mc C:\inetpub\wwwroot. y l th mc m Web Server mc nh nh x vo //localhost, do , cc trang web t trong wwwroot c th c truy cp bi cc my tnh khc. 1.4 To mi ng dng Web vi ASP.NET Lu hnh ni b Trang 12

Chng ta s bt u bng vic lm quen vi mi trng pht trin ng dng (IDE) ca Visual Studio.NET. VS.NET 2008 c nhiu thay i so vi cc bin bn trc. Hnh di l mn hnh khi u ca VS.NET 2008. Vng lm vic chnh gia ang hin th trang Start Page, Recent Projects, Visual Studio Developer News. Visual Studio Developer News cn mt kt ni vi Internet download cc thng tin t website ca Microsoft v my tnh ca chng ta. Recent Projects lit k cc project m chng ta lm vic trong thi gian gn y. Trn mc ny, chng ta cng c th to mi mt project bng cch nhn vo nt New Project.

Hnh 1.13 : Ca s giao din MS Visual Studio .NET 2008 1.4.1 To ng dng ASP.NET u tin Chng ta c th to ng dng Asp.Net s dng Visual C# Project theo cc bc sau: Bc 1. Chn t thc n File | New | WebSite. Xut hin hp thoi to mi Project (hnh 1.14). Chn loi Language l Visual C# Chn ASP.Net Web Site t vng Templates ng dng mi c to mc nh c tn l WebSiteXX (XX l s th t t ng). Chng ta c th thay i tn ca Project ti mc Location. Trong v d ny, chng ta thay i tn Project WebSite1 thnh MinhHoa.

Ti mc Location : Trang 13

Lu hnh ni b

Nu ta chn gi tr l File System th ng dng s c to ra trong th mc theo ng dn m ta ch nh v d : D:\DotNet2008\WebSite1, khi ta chy ng dng th VS.Net s to ra mt Web Server o v s dng Web server ny thc thi ng dng.

Hnh 1.14: Mn hnh to mi WebSite Nu nh ta chn gi tr l HTTP,ch ta g vo ng dn: http://localhost/WebSite1 th ng dng s c to ra trong th mc mc nh l C:\Inetpub\wwwroot vi tn l WebSite1, khi ta chy ng dng th VS.Net s s dng Web server l IIS m ta ci t trn my. 1.4.2 Thit k giao din thc thi v ng dng Trn hp cng c (Toolbox), nu cha c hp cng c chn View/ToolBox , m th Standard (cha cc Web Server Control) click vo ln lt hai iu khin (Control) nhn (Label) v dn vo trang Default.aspx. Nhp ni dung thuc tnh Text cho hai iu khin dng nhn theo bng 1.1 Bng 1.1: Tn iu khin lblChao lblThoiGian [Chui rng] Thuc tnh Text Cho bn n vi lp trnh ASP.Net 3.5

Lu hnh ni b

Trang 14

thanh cng c

phn m HTML

phn giao din

Hnh 1.15: Mn hnh thit k trang Default.aspx vit lnh cho trang Default.aspx cc bn vo menu View | Code hay nhn phm F7 , mn hnh vit lnh xut hin nh hnh 4.10 v vit lnh cho s kin Page_Load :
namespace MinhHoa { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblThoiGian.Text = "Ngy gi hin hnh" + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"); } } }

Thc hin vic gn ni dung cho thuc tnh Text ca iu khin nhn lblThoiGian nh trong hnh. Nhn F5 hoc Ctrl + F5 thi hnh ng dng. ng dng s c bin dch (compiler) kim tra li v hin ni dung ra trnh duyt mc nh trn my Kt qu nh hnh 1.16.

Lu hnh ni b

Trang 15

Hnh 1.16: Mn hnh kt qu hin th trang Default.aspx 1.5 Kho st giao din Visual Studio .NET 2008 Solution Explorer Hin th ca s Solution Explorer: menu View | Solution Explorer

Hnh 1.17 Ca s Solution Explorer y l ca s qun l cc "ti nguyn" c trong ng dng. Thng qua ca s ny, chng ta c th: Thc hin cc chc nng: sao chp, ct, dn trn tp tin, th mc nh Windows Explorer. T chc th mc qun l ng dng: S dng chc nng Add | New Folder t thc n ng cnh. Thm thnh phn mi cho ng dng: S dng chc nng Add | Add New Itemt thc n ng cnh. Xut hin hp thoi Add New Item, hnh 1.18 o o o Web Form: Thm trang Web Class: Thm lp i tng Web User Control: Thm iu khin ngi dng,....

Lu hnh ni b

Trang 16

Hnh 1.18: Mn hnh thm mi Item Xc nh trang web khi ng cho ng dng trong trng hp chng ta c nhiu trang web o Chn trang cn khi ng -> Nhp chut phi (xut hin thc n ng cnh) -> Chn Set As Start Page. o Xc nh Project khi ng (trong trng hp Solution c nhiu Project): Chn Solution v t (thc n) menu ng cnh chn Set as StartUp Project t thc n ng cnh.

Hnh 1.19 Chn trang thc thi u tin trong ng dng Property Window o Hin th ca s Properties Window: Thc n View | Properties Window. Lu hnh ni b Trang 17

o Thng qua ca s thuc tnh, chng ta c th thit lp thuc tnh cho trang web v cc i tng c trong trang web. Hnh 1.20 Toolbox o Hin th Toolbox: Thc n View | Toolbox

Hnh 1.20: Web Server Control

Lu hnh ni b

Trang 18

BI THC HNH CHNG 1: Bi 1: To ng dng cho php ngi dng la chn mu a thch trn trang ASP.NET nh sau:

Giao din ca chng ta c 3 checkbox v mt button. Khi button c click th hm x l s kin button click c thc hin v kim tra checkbox no c chn v hin th ni dung tng ng ln. Hng dn: Chng ta c file aspx nh sau: phn ni dung trong th <form> c nhp v ko th cc iu khin CheckBox v Button trong th HTML ca hp cng c.

Ni dung trang Default.aspx :


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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">

Lu hnh ni b

Trang 19

<head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> Bn thch nhng mu no? <br /> <input id="red" type="checkbox" runat="server" /> <br /> <input id="blue" type="checkbox" runat="server" /> Xanh dng <br /> <input id="green" type="checkbox" runat="server" /> Xanh lc <br /> <input id="Button1" type="button" value="Submit" OnServerClick="submit" runat="server"/> <p id="p1" runat="server" /> </form> </body> </html>

Code x l pha server nh sau:


public partial class _Default : System.Web.UI.Page { protected void submit(object sender, EventArgs e) { string sResult =""; if (red.Checked) sResult = ", "; if (green.Checked) sResult = sResult + "xanh lc, "; if (blue.Checked) sResult = sResult + "xanh dng"; p1.InnerHtml = "Bn thch mu: " + sResult; red.Checked = false; green.Checked = false; blue.Checked = false; } }

Lu hnh ni b

Trang 20

Chng 2 :

Tm hiu v s dng cc Server Controls

Trong bi ny, chng ta tp trung tm hiu cc loi Server controls. Cc vn chnh s c cp : Cu trc mt trang ASP.NET Bin c ca trang ASP.NET Gii thiu ASP.NET Server Controls Cc loi HTML Server Controls v Web server Controls Thuc tnh IsPostBack ca trang ASP.NET v AutoPostBack ca cc Web Server Controls Kt thc bi ny cc bn c th : S dng c cc Web Server Controls xy dng cc trang ASP.NET. 2.1 Cu trc trang ASP.NET Chng ta to mt trang ASP.NET tn ChaoMung.aspx, nhp chn File|New|File (hoc Ctrl+N), hoc trong ca s Solution Explorer nhp R-Click|Add New Item .., xut hin hp thoi sau :

Hnh 2.1 Hp thoi thm thnh phn mi vo ng dng ang m. Chn mc Web Form, nhp Name : ChaoMung.aspx, nhp nt Add, mt trang mi c thm vo ng dng. 2.1.1 Cc phng php vit m trong ASP.NET ASP.NET cho php vit m lnh theo 2 m hnh sau: M hnh Code Inline (Code Inline Model) M hnh Code Behind (Code Behind Model)

Hnh 2.2 Trang ChaoMung.aspx mi c thm vo Lu hnh ni b Trang 21

Code Inline Model: Trong m hnh ny, phn m ASP.NET v m HTML c vit trong cng mt trang, m ASP.NET c vit phn <script runat="server">.</script> nm trong trang ASP.NET nhng khng trn ln vi m HTML dnh cho phn ni dung (content section). Chng hn nh ta c th t phn m trong trang ChaoMung.aspx ln trn cng tch khi phn m HTML .
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ChaoMung.aspx.cs" Inherits="ChaoMung" %> <!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"> <%-- Phn m ASP.NET(code section) --%> <script runat="server" language="c#"> void Page_Load(object sender, EventArgs e) { lblChao.Text = "Lp trnh Web vi ASP.Net 3.5"; } </script> <%-- Phn m HTML(content section) --%> <head runat="server"> <title>Chao mung</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lblChao" runat="server" Width="302px" Height="38px"> </asp:Label> </div> </form> </body> </html>

Kt qu thc thi trang trn :

Hnh 2.3 Minh ha phn HTML code ca trang ChaoMung.aspx

Code Behind Model: Trang 22

Lu hnh ni b

Trong m hnh ny, phn m ASP.NET c c sp xp trong mt tp tin khc ring bit vi phn m HTML. Ta c th vit m theo x l bin c cho trang ChaoMung.aspx theo cc bc sau: Bc 1: Trong ca s Solution Explorer, chn trang ChaoMung.aspx ,nhn phi chut v chn ViewCode . Bc 2: Sau khi VS.Net to mt tp tin tn l ChaoMung.aspx.cs ta vit lnh : lblChao.Text = "Lp trnh Web vi ASP.Net 3.5" vo trong s kin Page_Load .
public partial class ChaoMung : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblChao.Text = "Lp trnh Web vi ASP.Net 3.5"; } }

Kt qu nh trn :

Hnh 2.4 Minh ha phn Code behind ca trang ChaoMung.aspx So vi CodeInline th Code Behind vit m lnh (code) d hn do tch c phn giao din v phn m HTML ring bit ng thi c th s dng li cc on m vit (reuseable codes) trong tp tin .aspx.cs 2.1.2 Cu trc ca trang ASP.NET Mt trang ASP.NET thng thng gm 3 phn: Phn 1: c gi l Page Directives, phn ny cung cp cho ASP.NET nhng thng tin c bit trnh bin dch bit cch thc thi trang ASP.NET, cng nh nhng thng tin dng trong tin trnh bin dch (during the compiling process), gm cc thng tin sau:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ChaoMung.aspx.cs" Inherits="ChaoMung" %>

<%@ Page %> : Khai bo cc bin dch trang. Language : khai bo ngn ng c s dng vit m cho trang (C#, VB.Net) AutoEventWireup: nu gi tr l true th cc s kin ca trang c t ng gi ng tn nh Page_Load m khng cn khi to s kin ch n phng thc Page_Load. CodeFile : Ch r tn tp tin code behind c phn m rng .aspx.cs (cha cc on m thc thi cc bin c) c lin kt vi trang ASP.NET c phn m rng .aspx. Inherits : Cho bit l trang giao din tha k t lp no l tn ca lp (class) ca tp tin code behind, theo th d l trang ChaoMung.aspx.cs. Phn 2: <script runat="server"> ... </script>, phn ny cn gi l Code Declaration Block, ging nh m pha client (Client Side) nhng c km theo thuc tnh runat="server" cho bit on m ny c thc thi pha server (Server Side). Ta c th t phn ny bt c Lu hnh ni b Trang 23

ni no trong trang web , nhng phn bit m ca ASP.NET vi m ca HTML ta nn sp xp phn u tin ca trang.
<script runat="server" language="c#"> void Page_Load(object sender, EventArgs e) { lblChao.Text = "Lp trnh Web vi ASP.Net 3.5"; } </script>

Phn m ny to ra mt phng thc (hm) c tn l Page_Load mc nh (default) cho cc trang ASP.NET, phng thc ny s thc hin gn chui "Lp trnh Web vi ASP.Net 3.5" vo trong thuc tnh Text ca Label Control mi khi trang c thc thi. Phn 3: <html>... <html>, y l ni ta bt u phn m ca HTML. Phn ny chnh l hnh thc trnh by ni dung ca trang c son bi m ASP.NET trc khi gi v v hin th trong trnh duyt (browser) ca Client. Ngoi ra, ASP.NET cng cho php ta km theo nhng ch th (instructions) trong Code Render Block bt u vi <% v kt thc vi %> Bi thc hnh 2_1: Xy dng mt ng dng Web vi tn WebSiteChap2_1 c cc thnh phn sau :

thm th mc App_Code, R-Click trn tn ng dng trong ca s Solution Explorer, chn Add ASP.NET folder v chn tip App_Code :

Sau to mt lp Product.cs trong th mc App_Code , R-Click trn th mc App_Code, chn Add New Item :

Lu hnh ni b

Trang 24

G tn trong khung Name l Product.cs v nhp ni dung sau :


// Define the delegate that represents the event. public delegate void PriceChangedEventHandler(); public class Product { private string name; private decimal price; private string imageUrl; public string Name { get { return name; } set { name = value; } } // Define the event. public event PriceChangedEventHandler PriceChanged; public decimal Price { get { return price; } set { price = value; // Fire the event, provided there is at least one listener. if (PriceChanged != null) { PriceChanged(); } } } public string ImageUrl { get { return imageUrl; } set { imageUrl = value; } } public string GetHtml() { string htmlString; htmlString = "<h1>" + name + "</h1><br>"; htmlString += "<h3>Costs: " + price.ToString() + "</h3><br>"; htmlString += "<img src='" + imageUrl + "' />"; return htmlString;

Lu hnh ni b

Trang 25

} public Product(string name, decimal price) { Name = name; Price = price; } }

Vit m lnh cho trang Default.aspx :


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> private void Page_Load(object sender, EventArgs e) { Product saleProduct = new Product("Kitchen Garbage", 49.99M); saleProduct.ImageUrl = "garbage.jpg"; Response.Write(saleProduct.GetHtml()); } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Product Test</title> </head> <body> </body> </html>

Kt qu thc thi :

2.2 Bin c ca trang ASP.NET Khi lm vic vi trang ASP.NET, bn c th bt gp mt s bin c ca trang theo th t nh sau : PreInit, Init, InitComplete, PreLoad, Load, LoadComplete, PreRender, PreRenderComplete, UnLoad. khai bo cc bin c trang ASP.NET, bn vo thc n View|Component Design hay RClick| View Component Design trong ca s Solution Explorer. Lu hnh ni b Trang 26

Sau , nhp chn biu tng event ( ca trang s c hin ra nh hnh 2.5

) trong ca s Properties, danh sch cc bin c

Hnh 2.5 Danh sch cc bin c ca trang ASP.NET Init S kin Page_Init xy ra u tin khi trang web c yu cu. Load S kin ny l ni m bn s t phn ln cc x l, gi tr khi ng ban u cho trang web. S kin ny lun xy ra mi khi trang web c yu cu. PreRender S kin ny xy ra khi trang Web chun b c tr v cho Client. Unload S kin ny i lp vi s kin Page_Init. Nu nh s kin Page_Init xy ra u tin khi trang Web c yu cu, th y, Page_Unload l x kin sau cng, xy ra sau tt c nhng s kin khc. Th d 2-1: Khai bo cc bin c trang ASP.NET (Default.aspx.cs)
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Page.Response.Write("Page_Load <br/>"); } private void InitializeComponent() { this.PreRenderComplete += new System.EventHandler(this.Page_PreRenderComplete); this.PreLoad += new System.EventHandler(this.Page_PreLoad); this.Unload += new System.EventHandler(this.Page_Unload); this.InitComplete += new System.EventHandler(this.Page_InitComplete); this.Init += new System.EventHandler(this.Page_Init); this.PreRender += new System.EventHandler(this.Page_PreRender); this.Load += new System.EventHandler(this.Page_Load);

Lu hnh ni b

Trang 27

this.PreInit += new System.EventHandler(this.Page_PreInit); this.LoadComplete += new System.EventHandler(this.Page_LoadComplete); } protected void Page_Init(object sender, EventArgs e) { Page.Response.Write("Page_Init <br/>"); } protected void Page_InitComplete(object sender, EventArgs e) { Page.Response.Write("Page_InitComplete <br/>"); } protected void Page_LoadComplete(object sender, EventArgs e) { Page.Response.Write("Page_LoadComplete <br/>"); } protected void Page_PreInit(object sender, EventArgs e) { Page.Response.Write("Page_PreInit <br/>"); } protected void Page_PreLoad(object sender, EventArgs e) { Page.Response.Write("Page_PreLoad <br/>"); } protected void Page_PreRender(object sender, EventArgs e) { Page.Response.Write("Page_PreRender <br/>"); } protected void Page_PreRenderComplete(object sender, EventArgs e) { Page.Response.Write("Page_PreRenderComplete <br/>"); } protected void Page_Unload(object sender, EventArgs e) { } }

Kt qu sau khi thc thi trang trn :

Hnh 2.6 Danh sch cc bin c ca trang ASP.NET 2.3 Gii thiu ASP.NET Server Controls gip cho vic pht trin cc ng dng web nhanh chng v thun tin, ASP.NET cung cp cho chng ta mt tp hp cc iu khin sn c thc hin hu ht cc cng vic ph bin hng ngy. Cc iu khin ny chia lm 2 loi: HTML Server Control v ASP.NET Server Control. HTML Server Control : tin thn l th HTML m ta vn to trong trang HTML, ch khc mt iu l c thm runat = server; trong khai bo th v c thc thi ti Web Server. Cc i tng th HTML server controls khai bo trong namespace System.Web.UI.HtmlControls c ly t lp c s HtmlControl . Th d : <input type="submit" value="OK" ID="Convert" runat="server" OnServerClick="Convert_ServerClick" /> Web server controls: nm trong namespace System.Web.UI.WebControls. Cc control ny cng gi l Web Controls. Lu hnh ni b Trang 28

Th d : <asp:dropdownlist ID="lstBackColor" runat="server" Height="22px" Width="194px"></asp:dropdownlist> im khc bit gia HTML Server control v ASP.NET Server control ch: nh x ti th HTML(Mapping to HTML tags): HTML server controls nh x trc tip ti th HTML, n c chuyn i thnh server control bng vic dng thuc tnh runat = server. Web control khng nh x trc tip ti th HTML. Do bn phi s dng thm cc control ca ASP.NET. M hnh hng i tng(Object Model): HTML server control thit lp cc thuc tnh dng cp chui tn/gi tr khng nh kiu mnh. Web control thit lp theo chun thuc tnh (property). Trnh duyt ch (Target browser): HTML server control khng thay i ph thuc vo trnh duyt ch cn m bo control tr v ng vi trnh duyt. Web control tr v u ra t ng iu chnh ph thuc vo trnh duyt ch chc chn control tr v ng vi trnh duyt. 2.4 HTML Server Controls Nh trnh by trn, HTML Server Control bao gm cc th HTML c khai bo thm thuc tnh runat="server"

Hnh 2.7 Cc HTML Server Controls. HTML Server Controls bao gm hai nhm chnh thuc lp HtmlControl l : HTMLInputControl, HTMLContainerControl v ba iu khin ph l HTMLImage, HTMLLink v HTMLTitle theo m hnh cu trc phn cp sau :

Lu hnh ni b

Trang 29

Hnh 2.8 Cu trc lp HTMLControl. Cc thuc tnh chnh trong khai bo cc th HTMLControl trn da theo bng sau :

Hnh 2.9 Cc thuc tnh chnh ca cc HTMLControls. Cc s kin chnh ca cc th HTMLControl chia theo bng sau :

Lu hnh ni b

Trang 30

Hnh 2.10 Cc s kin ca HTMLControl. Kho st chi tt cc HTML Server Controls. 1. HtmlAnchor HtmlAchor control c s dng tng t nh mt th HTML <a>. Trong HTML, th <a> c s dng to mt Hyperlink. Hyperlink ny c th link ti mt bookmark hoc ti mt trang web khc. Cc thuc tnh : Thuc tnh M t Tr v tt c tn thuc tnh v gi tr tng ng ca th. Attributes Gi tr boolean xc nh control khng/c hin th (disabled) trn trang Disabled hay khng. Mc nh l false. a ch URL ca lin kt (link). Href Id duy nht ca control. Id in vo hay tr v ni dung gia th ng v th m, nhng k t c innerHtml bit th khng t ng chuyn thnh cc thc th (entities). in vo hay tr v ni dung gia th ng v th m. Nhng k t c innerText bit t ng chuyn thnh cc thc th (entities). Tn ca th. Name Tn hm c thc thi khi link c click. OnServerClick Xc nh rng control ny l server control. Phi c xc nh l Runat server. Xc nh hay tr v thuc tnh CSS c p dng cho control. Style Tr v tn ca th. TagName Xc nh ca s s c m. Target Ta s c hin th. Title Gi tr boolean xc nh control s c hin th hay khng. Visible Chng ta c trang aspx nh sau:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <a id="link1" href="http://dantri.com">Bo Dn Tr</a> <br /> <a id="link2" runat="server">Bo vnexpress</a>

Lu hnh ni b

Trang 31

</div> </form> </body> </html>

Code x l pha server nh sau:


public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { link2.HRef = "http://vnexpress.net"; link2.Target = "_blank"; } }

Chng ta c link1 gn thuc tnh href c gn trc tip trong th <a> cn link2 chng ta gn href khi trang c ti ln m lnh pha server.

2. HtmlButton. HtmlButton c s dng tng ng vi th HTML <button>. Trong HTML, th <button> c s dng to mt nt bm. Cc thuc tnh: Thuc tnh M t Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th . Attributes Gi tr boolean xc nh control khng/c hin th (disabled) trn trang Disabled hay khng. Mc nh l false. Id duy nht ca control. Id in vo hay tr v ni dung gia th ng v th m, nhng k t c innerHtml bit th khng t ng chuyn thnh cc entities. in vo hay tr v ni dung gia th ng v th m. Nhng k t c innerText bit t ng chuyn thnh cc entities. Tn hm c thc thi khi link c click. OnServerClick Xc nh rng control ny l server control. Phi c xc nh l Runat server. Xc nh hay tr v thuc tnh CSS c p dng cho control. Style Tr v tn ca th. TagName Gi tr boolean xc nh control s c hin th hay khng. Visible Chng ta c trang aspx nh sau:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

Lu hnh ni b

Trang 32

<!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 runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <button id="b1" style="background-color:#0000ff;height:25;width:100" runat="server" onserverclick="b1_Click"> Blue button! </button> <button id="b2" style="background-color:#fff0f5;height:25;width:100" runat="server" onserverclick="b2_Click"> Pink button! </button> <p id="p1" runat="server" /> </form> </body> </html>

Code x l pha server nh sau:


public partial class _Default : System.Web.UI.Page { protected void b1_Click(object sender, EventArgs e) { p1.InnerHtml = "bn click vo button mu xanh!"; } protected void b2_Click(object sender, EventArgs e) { p1.InnerHtml = "bn click vo button mu hng!"; } }

Giao din chng ta c hai button mt button mu xanh v mt button mu hng. Khi chng ta click vo button th hm x l s kin tng ng s gn ni dung vo th p v hin ln giao din nh hnh di y :

Lu hnh ni b

Trang 33

3. HtmlForm HtmlForm control c s dng tng ng th HTML <form>. Trong HTML, th <form> c s dng to mt form. Cc thuc tnh: Thuc tnh M t URL ni m d liu c gi n khi form c submit Action Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Attributes Gi tr boolean xc nh control c b disabled hay khng. Mc nh l false Disabled Id duy nht ca control Id in vo hay tr v ni dung gia th ng v th m. nhng k t c bit innerHtml th khng t ng chuyn thnh cc entities in vo hay tr v ni dung gia th ng v th m. Nhng k t c bit innerText t ng chuyn thnh cc entities Xc nh cch post d liu ln server. C 2 gi tr l post v get. Mc Method nh l post Tn ca form Name Xc nh rng control ny l server control. Phi c xc nh l server Runat Xc nh hay tr v thuc tnh CSS c p dng cho control Style Tr v tn ca th TagName Ca s load URL Target Gi tr boolean xc nh control s c hin th hay khng. Visible Chng ta c file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> Nhp tn ca bn: <input id="name" type="text" size="30" runat="server" /> <br /><br /> <input id="Submit1" type="submit" value="Submit" OnServerClick="submit_Click" runat="server" /> <p id="p1" runat="server" /> </form> </body> </html> Code x l pha server nh sau: public partial class _Default : System.Web.UI.Page { protected void submit_Click(object sender, EventArgs e) { Lu hnh ni b Trang 34

p1.InnerHtml = "Cho bn " + name.Value + "!"; } } Giao din chng ta c mt textbox v mt button. Khi chng ta click vo button submit th hm x l s kin submit_Click c thc hin v ghi ra trang web: cho bn cng vi tn c nhp vo textbox nh hnh di y:

4. HtmlGeneric. HtmlGeneric control c dng iu khin nhng th HTML khc cha c ch r bi mt HTML server control c bit, nh <body>, <div>, <span>, <font>, <p> Cc thuc tnh Thuc tnh M t Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Attributes Gi tr boolean xc nh control c b disabled hay khng. Mc nh l false Disabled Id duy nht ca control Id in vo hay tr v ni dung gia th ng v th m. nhng k t c bit innerHtml th khng t ng chuyn thnh cc entities in vo hay tr v ni dung gia th ng v th m. Nhng k t c bit innerText t ng chuyn thnh cc entities Xc nh cch post d liu ln server. C 2 gi tr l post v get. Mc Method nh l post Xc nh rng control ny l server control. Phi c xc nh l server Runat Xc nh hay tr v thuc tnh CSS c p dng cho control Style Tr v tn ca th TagName Gi tr boolean xc nh control s c hin th hay khng. Visible 5. HtmlImage. HtmlImage control c s dng tng ng th <img>. Trong HTML, th <img> c s dng hin th hnh nh. Cc thuc tnh Thuc tnh M t Xc nh v tr ca hnh: Align Top Middle Bottom Lu hnh ni b Trang 35

Left right M t ngn v hnh Alt Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Attributes dy ca vin xung quanh hnh Border Gi tr boolean xc nh control c b disabled hay khng. Mc nh l false Disabled Chiu cao ca hnh Height Id duy nht ca control Id Xc nh rng control ny l server control. Phi c xc nh l server Runat a ch URL ca hnh c hin th Src Xc nh hay tr v thuc tnh CSS c p dng cho control Style Tr v tn ca th TagName Gi tr boolean xc nh control s c hin th hay khng. Visible Chiu rng ca hnh Width Chng ta c file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <select id="select1" runat="server"> <option value="Smile.jpg">Mt ci</option> <option value="evil.jpg">Gin d</option> </select> <input id="Submit1" type="submit" runat="server" value="Hin th hnh" OnServerClick="choose_image"> <br /><br /> <img id="image1" src="Smile.jpg" runat="server" width="60" height="60" /> </form> </body> </html> Code x l pha server nh sau: public partial class _Default : System.Web.UI.Page { protected void choose_image(object sender, EventArgs e) { image1.Src = select1.Value; } } Giao din ca chng ta c mt combobox, mt button. Khi chng ta chn mt la chn khc trn combobox v click v button hin th th hnh nh hin th ln s thay i tng ng nh hnh di y : Lu hnh ni b Trang 36

6. HtmlInputButton. HtmlInputButton control c s dng iu khin cc th <input type=button>, <input type=submit>, v <input type=reset>. Trong HTML nhng th ny c s dng to mt nt lnh, mt submit button, v mt reset button. Cc thuc tnh: Thuc tnh M t
Attributes Disabled Name Runat Style TagName Type Value Visible Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Gi tr boolean xc nh control c b disabled hay khng. Mc nh l false Tn ca th Xc nh rng control ny l server control. Phi c xc nh l server Xc nh hay tr v thuc tnh CSS c p dng cho control Tr v tn ca th tag Loi th Gi tr ca th Gi tr boolean xc nh control s c hin th hay khng.

Th d phn ny chng ta c th xem li Th d mc HtmlButton. 7. HtmlInputCheckBox. HtmlInputCheckBox control c s dng iu khin th <input type=checkbox>. Trong HTML, th ny c s dng to mt checkbox. Cc thuc tnh v cc s kin: Thuc tnh M t
Attributes Checked Disabled Id Name Runat Style TagName Type Value Visible S kin ServerChange Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Gi tr boolean xc nh th c c chn hay khng. Gi tr boolean xc nh control c b disabled hay khng. Mc nh l false Id duy nht ca control Tn ca th Xc nh rng control ny l server control. Phi c xc nh l server Xc nh hay tr v thuc tnh CSS c p dng cho control Tr v tn ca th Loi th Gi tr ca th Gi tr boolean xc nh control s c hin th hay khng. M t Xy ra khi trng thi ca control thay i

Chng ta c file aspx nh sau: Lu hnh ni b Trang 37

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> Bn thch nhng mu no? <br /> <input id="red" type="checkbox" runat="server" /> <br /> <input id="blue" type="checkbox" runat="server" /> Xanh dng <br /> <input id="green" type="checkbox" runat="server" /> Xanh lc <br /> <input id="Button1" type="button" value="Submit" OnServerClick="submit" runat="server"/> <p id="p1" runat="server" /> </form> </body> </html>

Code x l pha server nh sau:


public partial class _Default : System.Web.UI.Page { protected void submit(object sender, EventArgs e) { string sResult =""; if (red.Checked) sResult = ", "; if (green.Checked) sResult = sResult + "xanh lc, "; if (blue.Checked) sResult = sResult + "xanh dng"; p1.InnerHtml = "Bn thch mu: " + sResult; red.Checked = false; green.Checked = false; blue.Checked = false; } }

Giao din ca chng ta c 3 checkbox v mt button. Khi button c click th hm x l s kin button click c thc hin v kim tra checkbox no c chn v hin th ni dung tng ng ln.

8. HtmlInputFile. Lu hnh ni b Trang 38

HtmlInputFile control c s dng iu khin th <input type=file>. Trong HTML, th ny c s dng upload mt file ln server. Cc thuc tnh Thuc tnh M t Danh sch nhng loi MIME c chp nhn Accept Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Attributes Gi tr boolean xc nh control c b disabled hay khng. Mc nh l false Disabled Id duy nht ca control Id S k t ti a c cho php trong th ny MaxLength Tn ca th Name Xc nh xem c truy xut c ti file c post ln khng PostedFile Xc nh rng control ny l server control. Phi c xc nh l server Runat Chiu rng ca th Size Xc nh hay tr v thuc tnh CSS c p dng cho control Style Tr v tn ca th TagName Loi th Type Gi tr ca th Value Gi tr boolean xc nh control s c hin th hay khng. Visible Chng ta c file aspx nh sau:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" method="post" enctype="multipart/form-data" runat="server"> <p> Chn file upload ln server: <input id="MyFile" type="file" size="40" runat="server"> </p> <p> <input id="Submit1" type="submit" value="Upload!" OnServerclick="submit" runat="server"> </p> <p> <div id="Div1" runat="server"> Tn file: <span id="fname" runat="server"/><br /> ContentLength: <span id="clength" runat="server"/> bytes </div> </p> </form> </body> </html>

Code x l pha server nh sau:


public partial class _Default : System.Web.UI.Page {

Lu hnh ni b

Trang 39

protected void submit(object sender, EventArgs e) { fname.InnerHtml = MyFile.PostedFile.FileName; clength.InnerHtml = MyFile.PostedFile.ContentLength.ToString(); MyFile.PostedFile.SaveAs("c:\\" + MyFile.PostedFile.FileName); } }

Giao din ca chng ta c mt HtmlInputFile control, mt HtmlButton control. Khi chng ta chn file upload ln server v nhn submit th hm x l s kin click ca button s c thc hin v s ly tn v ln ca file hin th ln trang web nh hnh di y

9. HtmlInputHidden. HtmlInputHidden control c s dng iu khin th <input type=hidden>. Trong HTML, th ny c s dng to mt hidden input field. Cc thuc tnh v s kin : Thuc tnh M t Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Attributes Gi tr boolean xc nh control c b disabled hay khng. Mc nh l false Disabled Id duy nht ca control Id Tn ca th Name Xc nh xem c truy xut c ti file c post ln khng PostedFile Xc nh rng control ny l server control. Phi c xc nh l server Runat Xc nh hay tr v thuc tnh CSS c p dng cho control Style Tr v tn ca th TagName Loi th Type Gi tr ca th Value Lu hnh ni b Trang 40

Gi tr boolean xc nh control s c hin th hay khng. Visible S kin M t ServerChange Khi ni dung ca th thay i Chng ta c file aspx nh sau:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> Nhp d liu: <input id="string1" type="text" size="25" runat="server" /> <input id="Submit1" type="submit" value="Submit" OnServerClick="submit" runat="server" /> <input id="hidden1" type="hidden" runat="server" /> <p id="p1" runat="server" /> </form> </body> </html>

Code pha server nh sau: public partial class _Default : System.Web.UI.Page { protected void submit(object sender, EventArgs e) { hidden1.Value = string1.Value; p1.InnerHtml="Hidden value= " + hidden1.Value; } } Giao din ca chng ta c mt HtmlInputHidden control, mt HtmlInputText control, mt HtmlInputButton. Khi chng ta click vo button submit th hm x l s kin click ca button c thc thi, khi gi tr ca hidden field s c gn bng gi tr ca textbox v sau hin th gi tr ca hidden field trong th p nh hnh sau y :

10. HtmlInputImage.

Lu hnh ni b

Trang 41

HtmlInputImage control c s dng iu khin th <input type=image>. Trong HTML, th ny c s dng to mt input button s dng hnh, thay cho loi button thng thng Cc thuc tnh Thuc tnh M t Cch sp xp ca hnh Align Text thay th hin th cho hnh Alt Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Attributes dy ca vin xung quanh ca th Border Gi tr boolean xc nh control c b disabled hay khng. Mc nh l false Disabled Id duy nht ca control Id Tn ca th Name OnServerClick Tn ca hm c thc thi khi hnh c click Xc nh rng control ny l server control. Phi c xc nh l server Runat Source ca image Src Xc nh hay tr v thuc tnh CSS c p dng cho control Style Tr v tn ca th TagName Loi th Type Gi tr ca th Value Gi tr boolean xc nh control s c hin th hay khng. Visible Chng ta c file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <p>Click vo mt hnh:</p> <p> <input id="Image1" type="image" src="Smile.jpg" OnServerClick="button1" runat="server" width="40" height="40" /> </p> <p> <input id="Image2" type="image" src="evil.jpg" OnServerClick="button2" runat="server" width="40" height="40" /> </p> <p id="p1" runat="server" /> </form> </body> </html> Code pha server nh sau:
public partial class _Default : System.Web.UI.Page { protected void button1(object sender, EventArgs e)

Lu hnh ni b

Trang 42

{ p1.InnerHtml = "Hnh mt ci c click"; } protected void button2(object sender, EventArgs e) { p1.InnerHtml = "Hnh mt gin d c click"; } }

Giao din ca chng ta c hai HtmlInputImage control. Khi chng ta click vo mi hnh th hm x l s kin click ca 2 hnh c thc thi v thng ip c hin ln trong th p nh hnh di y.

11. HtmlInputRadioButton. HtmlInputRadioButton c s dng iu khin th <input type=radio>. Trong HTML, th ny c s dng to mt radiobutton. Cc thuc tnh. Thuc tnh M t Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Attributes Gi tr boolean xc nh th c c chn hay khng Checked Gi tr boolean xc nh control c b disabled hay khng. Mc nh l false Disabled Id duy nht ca control Id Tn ca th Name Xc nh rng control ny l server control. Phi c xc nh l server Runat Xc nh hay tr v thuc tnh CSS c p dng cho control Style Tr v tn ca th TagName Loi th Type Gi tr ca th Value Gi tr boolean xc nh control s c hin th hay khng. Visible Chng ta c file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> Lu hnh ni b Trang 43

<!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <p>Chn mu bn a thch: <br /> <input id="r1" name="col" type="radio" runat="server" ></input> <br /> <input id="r2" name="col" type="radio" runat="server">Xanh lc</input> <br /> <input id="r3" name="col" type="radio" runat="server">Xanh dng</input> <br /> <input id="Button1" type="button" value="Submit" OnServerClick="submit" runat="server"/> <p id="p1" runat="server" /> </form> </body> </html> Code pha server nh sau: public partial class _Default : System.Web.UI.Page { protected void submit(object sender, EventArgs e) { string sColor=""; if(r1.Checked) sColor = ""; else if(r2.Checked) sColor = "Xanh lc"; else sColor = "Xanh dng"; p1.InnerHtml = "Bn thch mu: " + sColor; } } Giao din ca chng ta c 3 HtmlInputRadioButton, mt HtmlInputButton. Khi button submit c click th hm x l s kin click ca n c thc thi, nu radiobutton no c chn th mu tng ng s c hin th ln thng qua th p nh hnh di y :

Lu hnh ni b

Trang 44

12. HtmlInputText. HtmlInputText control c s dng iu khin 2 th <input type=text> v <input type=password>. Trong HTML, nhng th c s dng to mt text field v mt password field. Cc thuc tnh. Thuc tnh M t Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Attributes Gi tr boolean xc nh control c b disabled hay khng. Mc nh l false Disabled Id duy nht ca control Id S k t ti a c cho php ca th ny MaxLength Tn ca th Name Xc nh rng control ny l server control. Phi c xc nh l server Runat Chiu rng ca th Size Xc nh hay tr v thuc tnh CSS c p dng cho control Style Tr v tn ca th TagName Loi th Type Gi tr ca th Value Gi tr boolean xc nh control s c hin th hay khng. Visible Chng ta c th xem Th d mc HtmlButton. 13. HtmlSelect. HtmlSelect control c s dng iu khin th <select>. Trong HTML, th ny c s dng to drop-down list. Cc thuc tnh : Thuc tnh M t Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Attributes Tn ca bng d liu s dng DataMember Data source s dng DataSource Trng trong data source c hin thi trong drop-down list DataTextField Trng trong data source xc nh gi tr ca mi item trong drop-down DataValueField list. Gi tr boolean xc nh control c b disabled hay khng. Mc nh l Disabled Lu hnh ni b Trang 45

false Id duy nht ca control Id in vo hay tr v ni dung gia th ng v th m. nhng k t c bit innerHtml th khng t ng chuyn thnh cc entities in vo hay tr v ni dung gia th ng v th m. Nhng k t c innerText bit t ng chuyn thnh cc entities Danh sch ca nhng item trong drop-down list. Items Xc nh nhiu item c th c chn ti cng mt thi im Multiple OnServerChange Tn ca hm c thc thi khai item c chn b thay i Xc nh rng control ny l server control. Phi c xc nh l server Runat Index ca item c chn hin ti SelectedIndex Chiu rng ca th Size Xc nh hay tr v thuc tnh CSS c p dng cho control Style Tr v tn ca th TagName Gi tr ca th Value Gi tr boolean xc nh control s c hin th hay khng. Visible Chng ta xem Th d mc HtmlImage. 14. HtmlTable. HtmlTable control c s dng iu khin th <table>. Trong HTML th table c s dng to 1 table. Cc thuc tnh Thuc tnh M t Xc nh cch sp xp ca table Align Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Attributes Xc nh mu nn ca table BGColor Xc nh dy ca vin Border Xc nh mu ca border BorderColor Xc nh khong cch gia vin ca v ni dng bn trong CellPadding Xc nh khong cch gia cc CellSpacing Gi tr boolean xc nh control c b disabled hay khng. Mc nh l false Disabled Id duy nht ca control Id in vo hay tr v ni dung gia th ng v th m. nhng k t c bit innerHtml th khng t ng chuyn thnh cc entities in vo hay tr v ni dung gia th ng v th m. Nhng k t c bit innerText t ng chuyn thnh cc entities Tr v i tng HtmlRowCollection th hin tt c cc dng trong table Rows Xc nh hay tr v thuc tnh CSS c p dng cho control Style Tr v tn ca th TagName Gi tr boolean xc nh control s c hin th hay khng. Visible Xc nh chiu rng ca table Width Chng ta c trang aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title></head> Lu hnh ni b Trang 46

<body> <form id="Form1" runat="server"> <p>s dng: <select id="rows1" runat="server"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <br />s ct: <select id="cells1" runat="server"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <br /><br /> <input id="Submit1" type="submit" value="Hin th Table" runat="server" OnServerClick="submit"> </p> <table id="t1" border="1" runat="server" visible="false"/> </form> </body> </html> Code pha server nh sau:
public partial class _Default : System.Web.UI.Page { protected void submit(object sender, EventArgs e) { int row,numrows,numcells,j,i; row=0; numrows=int.Parse(rows1.Value); numcells=int.Parse(cells1.Value); for (j = 1; j <= numrows; j++) { HtmlTableRow r = new HtmlTableRow(); row = row + 1; for (i = 1; i <= numcells; i++) { HtmlTableCell c = new HtmlTableCell(); c.Controls.Add(new LiteralControl("Dng " + j + ", ct " + i)); r.Cells.Add(c); } t1.Rows.Add(r); t1.Visible = true; } } }

Giao din ca chng ta c 2 HtmlSelect control, mt HtmlInputButton. Ngi dng c th chn s dng v s ct ca table. Khi ngi dng click submit button th hm x l s kin button click c thc hin v sinh ra table vi s dng v s ct chng ta la chn.

Lu hnh ni b

Trang 47

15. HtmlTableCell. HtmlTableCell control c s dng iu khin th <td> v <th>. Trong HTML nhng th ny c s dng to nhng cell trong table v nhng cell header ca table. Cc thuc tnh Thuc tnh M t Sp xp theo chiu ngang ni dng ca mt cell Align Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Attributes Xc nh mu nn ca cell BGColor Xc nh dy ca vin. Border S ct ca cell c m rng. ColSpan Gi tr boolean xc nh control c b disabled hay khng. Mc nh l false. Disabled Id duy nht ca control. Id in vo hay tr v ni dung gia th ng v th m. nhng k t c bit InnerHtml th khng t ng chuyn thnh cc entities. in vo hay tr v ni dung gia th ng v th m. Nhng k t c bit InnerText t ng chuyn thnh cc entities. S dng ca cell c m rng. RowSpan Xc nh rng control ny l server control. Phi c xc nh l server. Runat Xc nh hay tr v thuc tnh CSS c p dng cho control. Style Tr v tn ca th. TagName Sp xp theo chiu dc ni dung ca cell. Valign Gi tr boolean xc nh control s c hin th hay khng. Visible Xc nh chiu rng ca cell. Width Chng ta c file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

Lu hnh ni b

Trang 48

<!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <table id="table1" border="1" runat="server"> <tr> <td>Cell 1</td> <td>Cell 2</td> </tr> <tr> <td>Cell 3</td> <td>Cell 4</td> </tr> </table> <br /> <input id="Button1" type="button" value="Thay i ni dung" OnServerClick="submit" runat="server"/> </form> </body> </html> Code pha server nh sau: public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void submit(object sender, EventArgs e) { int i,j; table1.BgColor="yellow"; table1.BorderColor="red"; for (i = 0; i <= table1.Rows.Count - 1; i++) for (j = 0; j <= table1.Rows[i].Cells.Count - 1; j++) table1.Rows[i].Cells[j].InnerHtml = "Row " + i; } } Giao din ca chng ta c mt HtmlTable control v mt HtmlInputButton control. Khi chng ta click vo submit button th hm x l s kin click ca button ny c thc hin, khi mu nn ca table c gn l mu vng, v vin ca table c gn li thnh mu nh hnh di y : Lu hnh ni b Trang 49

16. HtmlTableRow. HtmlTableRow control c s dng iu khin th <tr>. Trong HTML, th <tr> c s dng to table row. Cc thuc tnh: Thuc tnh M t Sp xp theo chiu ngang ni dng ca row Align Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Attributes Xc nh mu nn ca row BGColor Xc nh dy ca vin Border Tr v nhng cell trong row ny Cells Gi tr boolean xc nh control c b disabled hay khng. Mc nh l false Disabled Id duy nht ca control Id in vo hay tr v ni dung gia th ng v th m. nhng k t c bit InnerHtml th khng t ng chuyn thnh cc entities in vo hay tr v ni dung gia th ng v th m. Nhng k t c bit InnerText t ng chuyn thnh cc entities Xc nh rng control ny l server control. Phi c xc nh l server Runat Xc nh hay tr v thuc tnh CSS c p dng cho control Style Tr v tn ca th tag TagName Sp xp theo chiu dc ni dung ca row VAlign Gi tr boolean xc nh control s c hin th hay khng. Visible Chng ta c th xem Th d mc HtmlTableCell (15). 17. HtmlTextArea. HtmlTextArea control c s dng iu khin th <textarea>. Trong HTML, th ny c s dng to text area. Cc thuc tnh : Thuc tnh M t Tr v tt c tn thuc tnh v gi tr tng ng ca thuc th Attributes Gi tr boolean xc nh control c b disabled hay khng. Mc nh l Disabled false Id duy nht ca control Id Lu hnh ni b Trang 50

in vo hay tr v ni dung gia th ng v th m. nhng k t c bit th khng t ng chuyn thnh cc entities in vo hay tr v ni dung gia th ng v th m. Nhng k t c InnerText bit t ng chuyn thnh cc entities Tn duy nht ca text area Name OnServerChange Tn ca hm c thc thi khi ni dung ca textarea b thay i S dng hin th ca text area Rows Xc nh rng control ny l server control. Phi c xc nh l server Runat Xc nh hay tr v thuc tnh CSS c p dng cho control Style Tr v tn ca th tag TagName Ni dung ca textarea Value Gi tr boolean xc nh control s c hin th hay khng. Visible Chng ta c file aspx nh sau: InnerHtml <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> Nhp d liu:<br /> <textarea id="textarea1" cols="35" rows="6" runat="server" /> <input id="Submit1" type="submit" value="Submit" OnServerClick="submit" runat="server" /> <p id="p1" runat="server" /> </form> </body> </html> Code pha server nh sau: public partial class _Default : System.Web.UI.Page { protected void submit(object sender, EventArgs e) { p1.InnerHtml = "<b>You wrote:</b> " + textarea1.Value; } } Giao din ca chng ta gm c mt HtmlTextArea control, mt HtmlInputButton control. Khi button submit c click th hm x l s kin click ca n c thc hin, v thng ip chng ta ghi trong textArea s c in ra trong th p.

Lu hnh ni b

Trang 51

2.5 ASP.NET Server Controls Cng ging nh HTML server control, cc Web server control cng c to trn server, v chng c sn thuc tnh runat=server thc thi ti server. Tuy nhin, Web server control khng nht thit phi nh x ti bt k th HTML no tn ti v chng c th th hin nhng th c chc nng phc tp hn.

Hnh 2.12 Cc Web Server Control trn thanh toolbox. C php to mt Web server control l: <asp:control_name id="some_id" runat="server" /> Di y l cc l do bn nn s dng ASP.Net Web Control: n gin, tng t nh cc iu khin trn Windows Form. Lu hnh ni b Trang 52

ng nht: Cc iu khin Web server c cc thuc tnh ging nhau -> d tm hiu v s dng. Hiu qu: Cc iu khin Web Server t ng pht sinh ra cc tag HTML theo tng loi Browser. Cc controls ASP.Net l cc cc lp, do ta c th m rng cc chc nng ca cc control ( customize control ).

Cc Web Server Controls theo m hnh phn cp sau:

Lu hnh ni b

Trang 53

Hnh 2.13 Cu trc lp WebControl. Kho st chi tit cc Web Server Controls : 1. AdRotator. AdRotator control c s dng hin th tun t nhng hnh qung co trn trang web. Control ny s dng file XML lu tr thng tin qung co. File XML phi bt u v kt thc vi th <Advertisements>. Bn trong th <Advertisements> c th c nhiu th <Ad> Nhng th nm trong th <Ad> c lit k sau y: Th M t Ty chn. ng dn ti file hnh nh <ImageUrl> Ty chn. URL ti link nu ngi dng click vo qung co <NavigateUrl> <AlternateText> Ty chn. Text thay th cho hnh Ty chn. Loi qung co <Keyword> Ty chn. Hin th t l phn trm ca nhng ngi click <Impressions> Cc thuc tnh Thuc tnh M t AdvertisementFile Xc nh ng dn ti file XML ch thng tin qung co AlternateTextField Xc nh trng d liu c s dng thay cho Alt text Xc nh trng d liu c s dng thay cho thuc tnh ImageURL ImageUrlField Xc nh mt b lc gii hn nhng qung co sau nhng loi KeywordFilter Xc nh trng d liu c s dng thay cho thuc tnh NavigateUrl NavigateUrlField cho mt qung co Xc nh control l mt server control. Phi c xc nh l server Runat Xc nh ni m URL. Target Lu hnh ni b Trang 54

Chng ta c file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <asp:AdRotator ID="AdRotator1" AdvertisementFile="Ad1.xml" runat="server" OnAdCreated="change_url" target="_blank" /> <p><a href="ad1.xml" target="_blank">View XML file</a></p> </form> </body> </html> Code pha server nh sau: public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void change_url(object sender, AdCreatedEventArgs e) { e.NavigateUrl = "http://www.w3schools.com"; } } File XML nh sau: <?xml version="1.0" encoding="utf-8" ?> <Advertisements> <Ad> <ImageUrl>Smile.jpg</ImageUrl> <NavigateUrl>http://www.w3schools.com</NavigateUrl> <AlternateText>W3Schools Main Site</AlternateText> <Impressions>50</Impressions> <Keyword>elearning</Keyword> </Ad> <Ad> <ImageUrl>evil.jpg</ImageUrl> <NavigateUrl>http://www.w3schools.com/xhtml/default.asp</NavigateUrl> <AlternateText>XHTML Tutorial</AlternateText> <Impressions>50</Impressions> <Keyword>XHTML</Keyword> </Ad> </Advertisements> Kt qu thc thi nh hnh di y :

Lu hnh ni b

Trang 55

2. Button. Button control c s dng hin th nt nhn trn trang web. Push button c th l submit button hoc command button. Mc nh control ny l mt submit button. Submit button khng c tn lnh v n post trang web tr li server khi n c click. C th vit mt x l s kin iu khin vic hot ng khi button submit c click. Command button c mt tn lnh v cho php chung tao to nhiu control button trn trang C th vit mt qun l s kin iu khin vic hot ng khi command button c click. Cc thuc tnh Thuc tnh M t Xc nh nu trang c xc nhn khi button c click. CausesValidation CommandAgrument B sung thng tin v lnh thc hin. Ch ra lnh lin quan n s kin lnh CommandName Xc nh tn ca hm c thc thi khi mt button c click OnClientClick Xc nh URL ca trang post t trang hin ti khi button click PostBackUrl Xc nh control l mt server control. Phi c xc nh l server Runat Xc nh text trn button. Text UserSubmitBehavior Xc nh c hay khng mt button s dng c ch submit ca browser hay c ch postback ca ASP.NET Xc nh nhm nhng control, mt button gy ra s nh gi(ph ValidationGroup chun) khi n post back v server Lu hnh ni b Trang 56

Chng ta c file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <asp:Button id="button1" Text="Click me!" runat="server" OnClick="submit" /> </form> </body> </html> Code pha server nh sau: public partial class _Default : System.Web.UI.Page { protected void submit(object sender, EventArgs e) { button1.Style["background-color"] = "#0000ff"; button1.Style["color"] = "#ffffff"; button1.Style["width"] = "200px"; button1.Style["cursor"] = "pointer"; button1.Style["font-family"] = "verdana"; button1.Style["font-weight"] = "bold"; button1.Style["font-size"] = "14pt"; button1.Text = "You clicked me!"; } } Giao din ca chng ta c mt submit button control. Chng ta to mt hm qun l s kin cho s kin Click lm nhim v thay i text v style ca button nh hnh di y :

3. Canlendar. Calendar control c s dng hin th mt calendar trong trang web. Control ny hin th lch mt thng ngi dng chn ngy v di chuyn ti nhng thng sau v nhng thng trc. Cc thuc tnh: Lu hnh ni b Trang 57

Thuc tnh Caption CaptionAlign CellPadding CellSpacing DayHeaderStyle DayNameFormat DayStyle FirstDayOfWeek NextMonthText NextPrevFormat NextPreStyle OtherMonthDayStyle PrevMonthText runat

M t u ca lch Sp xp u ca lch Khong cch gia cc cell v ni dung Khong cch gia cc cell Style hin thi tn ca ngy nh dng hin th nhng tn ca ngy Style hin th ngy Xc ng ngy no l ngy u tun Text c hin th cho link ti thng tip theo nh dng link ti thng trc v thng tip theo Style hin th link ti thng trc v thng tip theo Style hin ngy m khng phi ngy hin ti Text hin thi link ti thng trc. Xc nh control l mt server control. Phi c xc nh l server Ngy c chn SelectedDate Nhng ngy c chn SelectedDates Style cho ngy c chn SelectedDayStyle Lm th no ngi dng chn mt ngy SelectionMode Text hin th link chn thng SelectMonthText Style cho link chn tun v thng SelectorStyle Text hin th cho link chn tun SelectWeekText Gi tr boolean xc nh cc ngy ca tun c c hin th hay ShowDayHeader khng Gi tr boolean xc nh li phn cch gia cc ngy c hin th ShowGridLines hay khng Gi tr boolean xc nh c hin link ti thng trc v thng tip ShowNextPrevMonth theo hay khng Gi tr boolean xc nh ta ca lch c hin hay khng ShowTitle nh dng ta ca lch TitleFormat Style ca ta ca lch TitleStyle Style cho ngy hin ti TodayDayStyle Ngy hin ti TodayDate Xc nh s dng th <th> cho nhng ngy ca tun(Th) thay UseAccessibleHeader cho th <td> Xc nh ngy hin ti c hin th trong lch hay khng VisibleDate Style cho nhng ngy cui tun WeekendDayStyle Tn ca hm c thc thi khi mi cell ngy c to OnDayRender Tn ca hm c thc thi khi ngi dng chn mt ngy, tun OnSelectionChanged hoc thng OnVisibleMonthChanged Tn ca hm c thc thi khi ngi dng di chuyn ti mt thng khc. Chng ta c file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

Lu hnh ni b

Trang 58

<!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <asp:Calendar ID="Calendar1" DayNameFormat="Full" runat="server"> <WeekendDayStyle BackColor="#fafad2" ForeColor="#ff0000" /> <DayHeaderStyle ForeColor="#0000ff" /> <TodayDayStyle BackColor="#00ff00" /> </asp:Calendar> </form> </body> </html> Trang aspx trn hin th mt lch, nhng ngy trong tun c ghi y bng mu xanh, cui tun c ghi bng mu trn nn vng, ngy hin ti c hin th vi mu nn l xanh lc nh hnh sau y :

Cho file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> Lu hnh ni b Trang 59

<asp:Calendar DayNameFormat="Full" runat="server" SelectionMode="DayWeekMonth" SelectMonthText="<*>" SelectWeekText="<->"/> <SelectorStyle BackColor="#f5f5f5" /> </asp:Calendar> </form> </body> </html> Trang aspx bn trn hin th lch vi cc ngy trong tun c ghi y , ngi dng c th chn mt ngy, mt tun v mt thng, ngy/tun/thng c chn c hin th vi mu nn l mu xm nh hnh di y :

4. CalendarDay. CalendarDay control th hin mt ngy trong mt calendar control. Cc thuc tnh : Thuc tnh M t Bin ngy ca ngy Date DayNumberText S ngy(th) ca ngy Xc nh ngy trong thng khc c c hin th hay khng IsOtherMonth Xc nh c th chn c ngy IsSelectable Xc nh ngy c c chn hay khng IsSelected Xc nh c phi l ngy hin ti hay khng IsToday Xc nh c phi l th by hay l ch nht hay khng. IsWeekend 5. CheckBox. CheckBox control c s dng hin th mt check box. Cc thuc tnh: Thuc tnh M t Xc nh form c t ng post back v server sau khi thuc tnh AutoPostBack Checked c thay i hay khng. Mc nh l khng Xc nh trang c c kim chng khi button control click hay khng CausesValidation Xc nh check box c chn hay khng. Checked Lu hnh ni b Trang 60

Tn v gi tr thuc tnh c s dng cho Input th cho CheckBox control Tn v gi tr thuc tnh c s dng cho Label th cho CheckBox LabelAttributed control Xc nh control l mt server control. Phi c xc nh l server Runat Text bn cnh CheckBox Text Text s c xut hin bn no check box(tri hay phi) TextAlign Nhm nhng control cho Checkbox control gy ra s kim chng khi ValidationGroup n post back v server OnCheckedChanged Tn ca hm c thc thi khi thuc tnh Checked c thay i Chng ta c file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <p>Home Phone: <asp:TextBox id="home" runat="server" /> <br /> Work Phone: <asp:TextBox id="work" runat="server" /> <asp:CheckBox id="check1" Text="Same as home phone" TextAlign="Right" AutoPostBack="True" OnCheckedChanged="Check" runat="server" /> </p> </form> </body> </html> Code pha server nh sau: public partial class _Default : System.Web.UI.Page { protected void Check(object sender, EventArgs e) { if (check1.Checked) work.Text = home.Text; else work.Text = ""; } } Giao din ca chng ta c 2 TextBox control v mt CheckBox contrel. Chng ta to mt hm qun l s kin cho s kin CheckedChanged sao chp ni dung ca textbox cha in thoi bn vo textbox ca in thoi c quan khi checkbox c chn . InputAttributes

Lu hnh ni b

Trang 61

6. CheckBoxList. CheckBoxList control c s dng to mt nhm check box vi nhiu la chn. Mi item c th c chn trong CheckBoxList control c nh ngha bng th ListItem. Cc thuc tnh: Thuc tnh M t Khong cch gia vin v ni dung CellPadding Khong cch gia cc cell CellSpacing S column s dng khi hin th nhm check box RepeatColumns Xc nh nhm check box s c lp li theo chiu ngang hay chiu dc RepeatDirection Layout ca check box group RepeatLayout Xc nh control l mt server control. Phi c xc nh l server Runat Xc nh text xut hin bn no ca check box TextAlign Chng ta c file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <asp:CheckBoxList id="check1" AutoPostBack="True" TextAlign="Right" OnSelectedIndexChanged="Check" runat="server"> <asp:ListItem>Item 1</asp:ListItem> <asp:ListItem>Item 2</asp:ListItem> <asp:ListItem>Item 3</asp:ListItem> <asp:ListItem>Item 4</asp:ListItem> <asp:ListItem>Item 5</asp:ListItem> <asp:ListItem>Item 6</asp:ListItem> </asp:CheckBoxList> <br /> <asp:label id="mess" runat="server"/> </form> </body> </html> Code pha server nh sau: public partial class _Default : System.Web.UI.Page { Lu hnh ni b Trang 62

protected void Check(object sender, EventArgs e) { int i; mess.Text = "<p>Selected Item(s):</p>"; for (i = 0; i <= check1.Items.Count - 1; i++) if (check1.Items[i].Selected) mess.Text += check1.Items[i].Text + "<br />"; } } Giao din ca chng ta c mt CheckBoxList control. Chng ta to mt hm qun l s kin cho s kin SelectedIndexChaged. Danh sch cc 6 check box. Khi chng ta chn mt mt trong nhng check box trang s t ng post back vef server, v hm x l s kin Check c thc thi. Vng lp s duyt qua tt c cc item v hin th trong trong label control nh hnh di y.

7. DropDownList. DropDownList control c s dng to mt drop-down list. Mi item trong DropDownList control c nh ngha bi mt th ListItem. Cc thuc tnh: Thuc tnh M t Index ca item c chn SelectedIndex OnSelectedIndexChanged Tn ca hm c thc thi khi index ca item c chn b thay i Xc nh control l mt server control. Phi c xc nh l runat server Chng ta c file aspx nh sau:

Lu hnh ni b

Trang 63

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DropDownList.aspx.cs" Inherits="DropDownList" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <asp:DropDownList id="drop1" runat="server"> <asp:ListItem>Item 1</asp:ListItem> <asp:ListItem>Item 2</asp:ListItem> <asp:ListItem>Item 3</asp:ListItem> <asp:ListItem>Item 4</asp:ListItem> <asp:ListItem>Item 5</asp:ListItem> <asp:ListItem>Item 6</asp:ListItem> </asp:DropDownList> <asp:Button ID="Button1" Text="Submit" OnClick="submit" runat="server"/> <p><asp:label id="mess" runat="server"/></p> </form> </body> </html> Code pha server nh sau: public partial class DropDownList : System.Web.UI.Page { protected void submit(object sender, EventArgs e) { mess.Text = "You selected " + drop1.SelectedItem.Text; } } Giao din ca chng ta c mt DropDownList control, mt button control. Chng ta to mt hm qun l s kin cho s kin Click trn button submit, hin th item c chn trong DropDownList.

8. HyperLink. Lu hnh ni b Trang 64

HyperLink control c s dng to mt hyperlink. Cc thuc tnh: Thuc tnh M t a ch URL hin th cho link ImageUrl a ch URL ca link NavigateUrl Xc nh control l mt server control. Phi c xc nh l server Runat Xc nh ca s s c m ra Target Text hin th cho link Text Chng ta c file aspx nh sau:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="HyperLink.aspx.cs" Inherits="HyperLink" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <asp:HyperLink ID="HyperLink1" ImageUrl="Smile.jpg" NavigateUrl="http://www.w3schools.com" Text="Visit W3Schools!" Target="_blank" runat="server" Width="80"/> </form> </body> </html>

Trang web ca chng ta c mt hnh l mt hyperlink.

9. Image. Image control l control c s dng hin th hnh nh. Cc thuc tnh Thuc tnh M t Lu hnh ni b Trang 65

Text thay th cho hnh AlternateText Ni dung m t chi tit cho hnh DescriptionUrl GenerateEmptyAlternateText Xc nh control c to ra mt chui rng cho alternate text hay khng Xc nh cch sp xp ca hnh ImageAlign Url ca hnh hin th ImageUrl Xc nh control l mt server control. Phi c xc nh l server runat

Chng ta c file asxp hin th hnh nh sau:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Image.aspx.cs" Inherits="Image" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <asp:Image ID="Image1" runat="server" AlternateText="W3Schools" ImageUrl="Smile.jpg"/> </form> </body> </html>

10. ImageButton. ImageButton control c s dng hin th mt hnh c th click c Lu hnh ni b Trang 66

Cc thuc tnh: Thuc tnh CauseValidation

M t Xc nh trang c kim chng ImageButton control c click Thng thng tin cho lnh thc hin CommandArgument Lnh c lin kt vi s kin lnh CommandName GenerateEmptyAlternateText Xc nh control c c to mt chui rng cho alternate text hay khng Tn ca hm c thc thi khi hnh c click OnClientClick URL ca trang post ti t trang hin ti khi ImageButton PostBackUrl control c click Xc nh control l mt server control. Phi c xc nh l Runat server TagKey Nhm nhng control m ImageButton control gy nn s ValidationGroup kim chng khi n post back v server Chng ta c file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImageButton.aspx.cs" Inherits="ImageButton" %> <!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 runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <p>Click ln hnh:</p> <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="Smile.jpg" OnClick="getCoordinates" Width="70" Height="70"/> <p><asp:label id="mess" runat="server"/></p> </form> </body> </html> Code pha server nh sau: public partial class ImageButton : System.Web.UI.Page { protected void getCoordinates(object sender, ImageClickEventArgs e) { mess.Text = "Ta : " + e.X + ", " + e.Y; } } Giao din chng ta c mt ImageButton control v mt label control. Khi ngi dng click vo image th th tc con getCoordinates c thc hin. Th tc ny tr v thng ip v tr ca click v thng ip ny c hin th ln label control.

Lu hnh ni b

Trang 67

11. Label. Label control c s dng hin th text trn mt trang. Cc thuc tnh: Thuc tnh M t Xc nh control l mt server control. Phi c xc nh l server Runat Text c hin th trn label Text C file aspx nh sau:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Label.aspx.cs" Inherits="Label" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> in ni dung: <asp:TextBox id="txt1" Width="200" runat="server" /> <asp:Button id="b1" Text="Submit" OnClick="submit" runat="server" /> <p><asp:Label id="label1" runat="server" /></p> </form> </body> </html>

Code pha server nh sau:


public partial class Label : System.Web.UI.Page { protected void submit(object sender, EventArgs e) label1.Text = txt1.Text; } } {

Giao din ca chng ta c mt label control, mt textbox control, v mt button control. Khi ngi dng click v button, th tc submit c thc hin. Th tc ny copy ni dung ca textbox control gn vo cho label control. Lu hnh ni b Trang 68

12. LinkButton. LinkButton control c s dng to mt hyperlink button. Cc thuc tnh: Thuc tnh M t Xc nh trang c kim chng LinkButton control c click CauseValidation CommandArgument Thng thng tin cho lnh thc hin Lnh c lin kt vi s kin lnh CommandName Tn ca hm c thc thi khi hnh c click OnClientClick URL ca trang post ti t trang hin ti khi LinkButton control c PostBackUrl click Xc nh control l mt server control. Phi c xc nh l server Runat Text trn LinkButton Text Nhm nhng control m LinkButton control gy nn s kim chng ValidationGroup khi n post back v server Chng ta c file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="LinkButton.aspx.cs" Inherits="LinkButton" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <asp:LinkButton ID="LinkButton1" Text="Click" OnClick="lblClick" runat="server" /> <p><asp:Label id="Label1" runat="server" /></p> </form> </body> </html> Code pha server nh sau: public partial class LinkButton : System.Web.UI.Page { protected void lblClick(object sender, EventArgs e) { Lu hnh ni b Trang 69

Label1.Text = "Bn click vo LinkButton control"; } } Giao din ca chng ta gm c mt LinkButton control, mt label control. Khi ngi dng click v link th th tc lbClick c thc thi. Th tc gn thng ip Bn click v LinkButton control vo Label control.

13. ListBox. ListBox control c s dng to mt drop-down list mt hoc nhiu la chn. Cc thuc tnh: Thuc tnh M t S dng c hin th trong list Rows Cho php chn mt hay nhiu item SelectionMode Chng ta c file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListBox.aspx.cs" Inherits="ListBox" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <asp:ListBox id="drop1" rows="3" runat="server"> <asp:ListItem selected="true">Item 1</asp:ListItem> <asp:ListItem>Item 2</asp:ListItem> <asp:ListItem>Item 3</asp:ListItem> <asp:ListItem>Item 4</asp:ListItem> <asp:ListItem>Item 5</asp:ListItem> <asp:ListItem>Item 6</asp:ListItem> </asp:ListBox> <asp:Button ID="Button1" Text="Submit" OnClick="submit" runat="server" /> <p><asp:label id="mess" runat="server" /></p> </form> </body> </html> Lu hnh ni b Trang 70

Code pha server nh sau: public partial class ListBox : System.Web.UI.Page { protected void submit(object sender, EventArgs e) { mess.Text = "Bn chn " + drop1.SelectedItem.Text; } } Giao din ca chng ta gm c mt ListBox control v mt Button control. To mt hm qun l s kin cho s kin Click hin th item c chn ra Label control.

14. ListItem. ListItem control to 1 item trong mt list. Control ny c dng cng vi nhng control nh l <asp:ListBox>, <asp:RadioButtonList>, v <asp:BulletedList> Cu trc: <asp:ListItem Enabled="True|False" Selected="True|False"Text="label" Value="value"/> Cc thuc tnh: Thuc tnh M t Ty chn. Tp hp ca cc cp tn v gi tr thuc tnh tng ng cho Attributes ListItem, Ty chn. Xc nh item enable hay disable Enable Ty chn. Xc nh item c c chn hay khng. Selected Ty chn. Text c hin th trong ListeItem Text Ty chn. Gi tr ca ListItem. Value Chng ta c th xem th d mc 13 (ListBox) 15. Literal. Literal control c s dng hin th text trn mt trang. Cc thuc tnh: Thuc tnh M t Mode Xc nh control l mt server control. Phi c xc nh l server Runat Text hin th Text Chng ta c trang aspx nh sau: Lu hnh ni b Trang 71

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Literal.aspx.cs" Inherits="Literal" %> <!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 runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <asp:Literal id="Literal1" Text="Hello !" runat="server" /> <br /><br /> <asp:Button ID="Button1" Text="Click " OnClick="submit" runat="server" /> </form> </body> </html>

Code pha server nh sau:


public partial class Literal : System.Web.UI.Page { protected void submit(object sender, EventArgs e) { Literal1.Text = "Hello world!"; } }

Giao din ca trang web chng ta gm c mt Literal control v mt Button control. Khi ngi dng click vo button, th th tc submit c thc hin, th tc ny thay i text ca Literal control.

16. Panel. Panel control c s dng nh l mt vt cha cho cc control khc. Cc thuc tnh: Thuc tnh M t Xc nh URL file hnh c hin th nh l background cho control ny BackImageUrl Xc nh ID ca button mc nh trong panel DefaultButton Xc nh hng hin th ni dung ca panel Direction Xc nh caption cho nhm nhng control trong panel GroupText HorizontalAlign Xc nh vic sp xp ni dung theo chiu ngang Xc nh control l mt server control. Phi c xc nh l server Runat Lu hnh ni b Trang 72

Xc nh v hin th ca scroll bar trong panel ScrollBars Xc nh ni dung c c bao li hay khng. Wrap Chng ta c file aspx nh sau:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Panel.aspx.cs" Inherits="Panel" %> <!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 runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:Panel id="panel1" runat="server" BackColor="#ff0000" Height="100px" Width="100px"> Hello World! </asp:Panel> <asp:CheckBox id="check1" Text="n Panel control" runat="server"/> <br /><br /> <asp:Button ID="Button1" Text="Load li" runat="server" /> </form> </body> </html>

Code pha server nh sau:


public partial class Panel : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (check1.Checked) panel1.Visible = false; else panel1.Visible = true; } }

Giao din ca chng ta gm c mt Panel control, mt CheckBox control v mt Button control. Khi ngi dng chn v CheckBox control, v click vo button Load li th Panel control s n i.

Lu hnh ni b

Trang 73

17. PlaceHolder. PlaceHolder control c s dng dnh khong trng cho nhng control khc thm vo bng code. Cc thuc tnh: Thuc tnh M t Runat Xc nh control l mt server control. Phi c xc nh l server 18. RadioButton. RadioButton control c s dng hin th radio button. Cc thuc tnh: Thuc tnh M t Gi tr boolean xc nh form cc c t ng post back v server sau AutoPostBack khi thuc tnh Checked b thay i hay khng. Mc nh l false Gi tr boolean xc nh radio button c c chn hay khng. Checked Gi tr duy nht cho control Id Tn ca group m radio button thuc v GroupName OnCheckedChanged Tn ca hm c thc thi khi thuc tnh Checked b thay i Xc nh control l mt server control. Phi c xc nh l server Runat Text bn cnh radio button Text Xc nh text xut hin bn pha no ca radio button TextAlign Chng ta c file aspx nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="RadioButton.aspx.cs" Inherits="RadioButton" %> <!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 runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> Chn mu bn thch: <br /> <asp:RadioButton id="red" Text="" Checked="True" GroupName="colors" runat="server"/> <br /> <asp:RadioButton id="green" Text="Xanh lc" GroupName="colors" runat="server"/> <br /> <asp:RadioButton id="blue" Text="Xanh dng" GroupName="colors" runat="server"/> <br /> <asp:Button ID="Button1" text="Submit" OnClick="submit" runat="server"/> <p><asp:Label id="Label1" runat="server"/></p> </form> </body> </html> Code pha server nh sau: Lu hnh ni b Trang 74

public partial class RadioButton : System.Web.UI.Page { protected void submit(object sender, EventArgs e) { if (red.Checked) Label1.Text = "Bn chn " + red.Text; else if (green.Checked) Label1.Text = "Bn chn " + green.Text; else if (blue.Checked) Label1.Text = "Bn chn " + blue.Text; } } Giao din ca chng ta c 3 RadioButton control, mt Button control, v mt Label control. Khi ngi dng click vo button submit th th tc submit c thc thi, th tc s kim tra xem radio button no c chn v gn gi tr: bn chn: cng vi thuc tnh Text ca RadioButton c chn.

19. RadioButtonList. RadioButtonList control c s dng to mt nhm nhng radio button. Mi item trong RadioButtonList control c nh ngha bi mt th ListItem. Cc thuc tnh: Thuc tnh M t Khong cch gia vin v ni dung bn trong ca mt cell CellPadding Khong cch gia cc cell CellSpacing RepeatColumns S ct s dng hin th nhm radio button RepeatDirection Xc nh hng nhm radio button hin th theo chiu dc hay theo chiu ngang Layout ca nhm cc radio button RepeatLayout Xc nh control l mt server control. Phi c xc nh l server Runat Xc nh text s xut hin bn pha no ca radio button TextAlign Chng ta c file aspx nh sau:

Lu hnh ni b

Trang 75

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RadioButtonList.aspx.cs" Inherits="RadioButtonList" %> <!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 runat="server"> <title></title></head> <form id="Form1" runat="server"> <asp:RadioButtonList id="radiolist1" runat="server"> <asp:ListItem selected="true">Item 1</asp:ListItem> <asp:ListItem>Item 2</asp:ListItem> <asp:ListItem>Item 3</asp:ListItem> <asp:ListItem>Item 4</asp:ListItem> </asp:RadioButtonList> <br /> <asp:Button text="Submit" OnClick="submit" runat="server"/> <p><asp:Label id="Label1" runat="server"/></p> </form> </html> Code phia server nh sau: public partial class RadioButtonList : System.Web.UI.Page { protected void submit(object sender, EventArgs e) { Label1.Text = "Bn chn " + radiolist1.SelectedItem.Text; } } Giao din ca chng ta gm c mt RadioButtonList control v mt Button control, v mt Label control. Chng ta to hm qun l s kin cho s kin Click hin th text v item c chn ln Label control.

20. BulletedList. BulletedList control to mt danh sch dng bullet. Mi item trong BulletedList control c nh ngha bi mt th ListItem. Lu hnh ni b Trang 76

Cc thuc tnh: Thuc tnh BulletImageUrl BulletStyle DisplayMode FirstBulletNumber

runat Target 21. Style. Style control c s dng xc nh style cho web control. Cc thuc tnh: Thuc tnh M t Mu nn ca control BackColor Mu vin ca control BorderColor Style vin ca control BorderStyle dy vin ca control BorderWidth Class Css c a ra bi control trn client CssClass Thuc tnh Font ca control Font Mu ca ch ForeColor Chiu cao ca control Height RegisteredCssClass Class CSS c ng k vi control Chiu rng ca control Width

M t Xc nh URL ca 1 custom bullet list image Xc nh Style ca Bullet list Xc nh loi danh sch c hin th Xc nh s bt u ca danh sch cc item trong danh sch c sp xp Xc nh control l mt server control. Phi c xc nh l server Xc nh ni m URL

22. Table. Table control c s dng vi TableCell v TableRow control to mt table Cc thuc tnh: Thuc tnh M t URL ca hnh c s dng lm nn ca table BackImageUrl Tn ca bng Caption Sp xp caption CaptionAlign Khong cch gia ni dung v vin ca cell CellPadding Khong cch gia cc cell CellSpacing nh dng gridline trong table GridLines HorizontalAlign Sp xp bng theo chiu ngang trn trang Tp hp tt c cc dng trong table Rows Xc nh control l mt server control. Phi c xc nh l server runat Chng ta c file aspx to mt table nh sau: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Table.aspx.cs" Inherits="Table" %> <!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 runat="server"> Lu hnh ni b Trang 77

<title></title> </head> <body> <form id="Form1" runat="server"> <asp:Table id="Table1" BorderWidth="1" GridLines="Both" runat="server" /> </form> </body> </html> Code pha server nh sau:
public partial class Table : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int rows, cells, j, i; rows = 3; cells = 2; for (j = 0; j <= rows - 1; j++) { TableRow r = new TableRow(); for (i = 0; i <= cells - 1; i++) { TableCell c = new TableCell(); c.Controls.Add(new LiteralControl("row " + j + ", cell " + i)); r.Cells.Add(c); } Table1.Rows.Add(r); } } }

23. TableCell. TableCell c s dng cng vi Table control v TableRow control to mt cell trong mt table. Cc thuc tnh Thuc tnh M t AssociatedHeaderCellID Mt danh sch cc table header cell lin h vi TableCell control S ct m cell m rng ColumnSpan Lu hnh ni b Trang 78

Sp xp ni dung theo chiu ngang trong table cell S dng m cell m rng Xc nh control l mt server control. Phi c xc nh l server Xc nh ni dung bn trong ca cell Text Sp xp ni dung theo chiu ngang trong table cell VerticalAlign Xc nh ni dung c c bao hay khng Wrap Chng ta c th xem th d mc 22 (Table) 24. TableRow. TableRow control c s dng cng vi TableCell v Table control to mt dng trong table. Cc thuc tnh: Thuc tnh M t Cells HorizontalAlign Sp xp ni dung theo chiu ngang trong table row nh v i tng TableRow trong table control TableSection Sp xp ni dung theo chiu dc trong table row VerticalAlign 25. TextBox. TextBox control c s dng to mt text box, ngi dng c th nhp liu. Cc thuc tnh: Thuc tnh M t AutoCompleteType Xc nh hnh v AutoComplete ca TextBox Gi tr boolean xc nh control ny c t ng post back v server khi AutoPostBack ni dung thay i hay khng. Mc nh l khng Trang s c kim chng khi Postback xy ra CausesValidation Chiu rng ca textbox Columns S lng k t ti a ca textbox Maxlength Xc nh ni dung trong textbox c c thay i hay khng ReadOnly Chiu cao ca textbox(ch c s dng khi TextMode=Multiline Rows Xc nh control l mt server control. Phi c xc nh l server Runat TagKey Ni dung ca textbox Text Xc nh loi TextBox control(SingleLine, MultiLine hay Password) TextMode Xc nh nhm nhng control c kim chng khi Postback xy ra ValidationGroup Gi tr boolean xc nh ni dung ca text box c c bao hay khng Wrap Tn hm c thc thi khi text trong textbox b thay i OnTextChange Chng ta c th xem th d mc 11 (Label) c s dng TextBox. 2.6 S kin PageLoad v thuc tnh IsPostBack Phn trnh by s da trn vic phn chia thnh request ln u v request t ln th hai tr i. Trng hp request ln u Nu ASP.NET 3.5 nhn request HTTP t Web browser, th n s to ra form instance. Form instance s to ra cy ca control instance bn trong . Sau , cho khi ng Load event, v gi ra event handler m chng ta s to. Trong event handler, set property ca control trong control cy kim sot vic hin th mn hnh. Cui cng, Form s sinh ra HTML v tr v Web browser. X l generate HTML c chuyn n control, control s sinh ra HTML ph HorizontalAlign RowSpan Runat Lu hnh ni b Trang 79

hp vi property ca chnh mnh. Hn na, c th lu gi trng thi ca control vo trong ViewState khi cn, v th <input type=hidden> s c to ra. Trng hp request t ln 2 tr i Ni dung cho n phn nhn request HTTP, to cy ca form instance v control instance th ging vi request u tin. Trong postback request bao gm ViewState to trong response trc , v th s set control property ging nh khi tr v response ln trc da vo ViewState . Sau , so snh trng thi gia HTTP request v trng thi control hin ti (c phc hi nh ViewState), th chng ta s khi ng event thch hp. Do form c load tng t vi trng hp request u tin, nn u tin, load event nu gi tr c input vo textbox khc vi ViewState, v nu TextChanged event, button c click, th chng ta cm gic nh l Clicked event. ng nhin, vi cc event handler ca load event m c request u tin, c postback (Page_Load() method) u c gi ra v iu kin th s dng IsPostBack property biu th l c postback hay khng, thay th ni dung x l. Thng thng Page_Load() method s nh sau :
protected void Page_Load(object sender, EventArgs e) { // S dng IsPostBack property, phn on xem c postback hay khng? if (!Page.IsPostBack) { // y s m t x l khi to. } // y s m t x l chung trong tt c event. }

Cc request sau ging vi request u tin. Control s to ra HTML, v ViewState lu gi trng thi s c sinh ra. Chng ta xt th d i tin US sang cc loi tin khc, c th nh sau :

Khi bn nhp s tin trong khung Convert, chn loi tin trong ComboBox v nhp nt OK. Kt qu nh sau :

Lu hnh ni b

Trang 80

Nhp nt Show Graph, kt qu nh sau :

Trang aspx c thit k nh sau : <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CurrencyConverter.aspx.cs" Inherits="CurrencyConverter" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" Lu hnh ni b Trang 81

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Currency Converter</title> </head> <body> <form ID="Form1" method="post" runat="server"> <div style="border-right: thin ridge; padding-right: 20px; border-top: thin ridge; padding-left: 20px; padding-bottom: 20px; border-left: thin ridge; width: 531px; padding-top: 20px; border-bottom: thin ridge; font-family: Verdana; background-color: #FFFFE8"> Convert: &nbsp; <input type="text" ID="US" runat="server" style="width: 102px" />&nbsp; U.S. dollars to &nbsp; <select ID="Currency" runat="server" /> <br /><br /> <input type="submit" value="OK" ID="Convert" runat="server" OnServerClick="Convert_ServerClick" /> <input type="submit" value="Show Graph" ID="ShowGraph" runat="server" OnServerClick="ShowGraph_ServerClick" /> <br /><br /> <img ID="Graph" alt="Currency Graph" scr="" runat="server" /> <br /><br /> <div style="font-weight: bold" ID="Result" runat="server"></div> </div> </form> </body> </html> Nhn thy th Select to ComboBox trn trang chn loi tin ban u l rng : <select ID="Currency" runat="server" /> v s c gn ni dung qua s kin Load ca trang CurrencyConverter .aspx khi trang c thc thi. Vic gn ny ch thc hin mt ln duy nht khi tho mn iu kin : this.IsPostBack == false tng ng vic request trang ln u tin. Phn m lnh thc thi pha server : public partial class CurrencyConverter : System.Web.UI.Page { protected void Page_Load(Object sender, EventArgs e) { if (this.IsPostBack == false) { // The HtmlSelect control accepts text or ListItem objects. Currency.Items.Add(new ListItem("Euros", "0.85")); Currency.Items.Add(new ListItem("Japanese Yen", "110.33")); Currency.Items.Add(new ListItem("Canadian Dollars", "1.2")); } Graph.Visible = false; } protected void Convert_ServerClick(object sender, EventArgs e) { decimal amount; bool success = Decimal.TryParse(US.Value, out amount); if (success) { // Retrieve the selected ListItem object by its index number. ListItem item = Currency.Items[Currency.SelectedIndex]; Lu hnh ni b Trang 82

decimal newAmount = amount * Decimal.Parse(item.Value); Result.InnerText = amount.ToString() + " U.S. dollars = "; Result.InnerText += newAmount.ToString() + " " + item.Text; } else { Result.InnerText = "The number you typed in was not in the correct format. "; Result.InnerText += "Use only numbers."; } } protected void ShowGraph_ServerClick(object sender, EventArgs e) { Graph.Src = "Pic" + Currency.SelectedIndex.ToString() + ".png"; Graph.Visible = true; } } 2.7 Thuc tnh AutoPostBack ca mt s Web Server Controls Chng ta xt th d thit k mt thip, c th nh sau :

Khi bn thay i mt vi cc gi tr : background color, foreground color, font name, font size, border style, default picture hoc greeting text, nu thuc tnh AutoPostBack ca cc Lu hnh ni b Trang 83

Web Server Controls tng ng : <asp:TextBox>, <asp:dropdownlist>, <asp:radiobuttonlist>, <asp:checkbox> trn trang t gi tr = true, bn s thy vic hiu chnh thip s c cp nht ngay sau khi bn thay i. Gii thch : Mt web server control c thuc tnh AutoPostBack=true, c ngha l control s postback ti server mi khi user tng tc vi control (thuc tnh ny support cho mt s control ca ASP.NET nh CheckBox, TextBox, ListControl v default chng khng t ng postback ti server. Vi cc asp.net control khc nh Button ngm nh chng s postback ti server mi khi user tng tc vi chng). V vy cn phi thit lp thuc tnh ny = true cho checkbox chkAll nh on m khai bo di y, server c th nhn c tn hiu t control ny sau khi user tng tc. <asp:CheckBox ID="chkAll" runat="server" OnCheckedChanged="chkAll_CheckedChanged" AutoPostBack="true" /> Ni dung trang aspx nh sau :
<%@ Page language="c#" Inherits="GreetingCardMaker.GreetingCardMaker2" CodeFile="GreetingCardMaker2.aspx.cs" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Greeting Card Maker</title> </head> <body> <form id="Form1" runat="server"> <div> <div style="BORDER-RIGHT: thin ridge; PADDING-RIGHT: 20px; BORDER-TOP: thin ridge; PADDING-LEFT: 20px; FONT-SIZE: x-small; PADDINGBOTTOM: 20px; BORDER-LEFT: thin ridge; WIDTH: 293px; PADDING-TOP: 20px; BORDER-BOTTOM: thin ridge; FONT-FAMILY: Verdana; HEIGHT: 508px; BACKGROUNDCOLOR: lightyellow">Choose a background color:<br /> <asp:dropdownlist ID="lstBackColor" runat="server" Height="22px" Width="194px" AutoPostBack="True" onselectedindexchanged="ControlChanged"></asp:dropdownlist><br /> <br /> Choose a foreground (text) color:<br /> <asp:dropdownlist ID="lstForeColor" runat="server" Height="22px" Width="194px" AutoPostBack="True" onselectedindexchanged="ControlChanged"></asp:dropdownlist><br /> <br /> Choose a font name:<br /> <asp:dropdownlist ID="lstFontName" runat="server" Height="22px" Width="194px" AutoPostBack="True" onselectedindexchanged="ControlChanged"></asp:dropdownlist><br /> <br /> Specify&nbsp;a font size:<br /> <asp:textbox ID="txtFontSize" runat="server" AutoPostBack="True" ontextchanged="ControlChanged"></asp:textbox><br /> <br /> Choose a border style:<br />

Lu hnh ni b

Trang 84

<asp:radiobuttonlist ID="lstBorder" runat="server" Height="59px" Width="177px" Font-Size="X-Small" AutoPostBack="True" RepeatColumns="2" onselectedindexchanged="ControlChanged"></asp:radiobuttonlist><br /> <br /> <asp:checkbox ID="chkPicture" runat="server" Text="Add the Default Picture" AutoPostBack="True" oncheckedchanged="ControlChanged"></asp:checkbox><br /> <br /> Enter the greeting text below:<br /> <asp:textbox ID="txtGreeting" runat="server" Height="85px" Width="240px" TextMode="MultiLine" AutoPostBack="True" ontextchanged="ControlChanged"></asp:textbox><br /> <br /> <asp:button ID="cmdUpdate" runat="server" Height="24px" Width="71px" Text="Update" onclick="cmdUpdate_Click"></asp:button>&nbsp;</div> <asp:panel ID="pnlCard" style="Z-INDEX: 101; LEFT: 313px; POSITION: absolute; TOP: 16px" runat="server" Height="507px" Width="339px" HorizontalAlign="Center"><br />&nbsp; <asp:Label ID="lblGreeting" runat="server" Height="150px" Width="256px"></asp:Label> <br /><br /><br /> <asp:Image ID="imgDefault" runat="server" Height="160px" Width="212px" Visible="False"></asp:Image> </asp:panel> </div> </form> </body> </html>

Code pha server nh sau:


public partial class GreetingCardMaker2 : System.Web.UI.Page { protected void Page_Load(object sender, System.EventArgs e) { if (this.IsPostBack == false) { // Get the list of colors. string[] colorArray = Enum.GetNames(typeof(KnownColor)); lstBackColor.DataSource = colorArray; lstBackColor.DataBind(); lstForeColor.DataSource = colorArray; lstForeColor.DataBind(); lstForeColor.SelectedIndex = 34; lstBackColor.SelectedIndex = 163; // Get the list of available fonts and add them to the font list. InstalledFontCollection fonts = new InstalledFontCollection(); foreach (FontFamily family in fonts.Families) { lstFontName.Items.Add(family.Name); } // Set border style options.

Lu hnh ni b

Trang 85

string[] borderStyleArray = Enum.GetNames(typeof(BorderStyle)); lstBorder.DataSource = borderStyleArray; lstBorder.DataBind(); // Select the first border option. lstBorder.SelectedIndex = 0; // Set the picture. imgDefault.ImageUrl = "defaultpic.png"; } } private void UpdateCard() { // Update the color. pnlCard.BackColor = Color.FromName(lstBackColor.SelectedItem.Text); lblGreeting.ForeColor = Color.FromName(lstForeColor.SelectedItem.Text); // Update the font. lblGreeting.Font.Name = lstFontName.SelectedItem.Text; try { if (Int32.Parse(txtFontSize.Text) > 0) { lblGreeting.Font.Size = FontUnit.Point(Int32.Parse(txtFontSize.Text)); } } catch { // Ignore invalid value. } try { if (Int32.Parse(txtFontSize.Text) > 0) { lblGreeting.Font.Size =FontUnit.Point(Int32.Parse(txtFontSize.Text)); } } catch { // Ignore invalid value. } // Find the appropriate TypeConverter for the BorderStyle enumeration. TypeConverter cnvrt = TypeDescriptor.GetConverter(typeof(BorderStyle)); // Update the border style using the value from the converter. pnlCard.BorderStyle = (BorderStyle)cnvrt.ConvertFromString(lstBorder.SelectedItem.Text);

// Update the picture.

Lu hnh ni b

Trang 86

if (chkPicture.Checked == true) { imgDefault.Visible = true; } else { imgDefault.Visible = false; } // Set the text. lblGreeting.Text = txtGreeting.Text; } protected void ControlChanged(Object sender, EventArgs e) { // Refresh the greeting card (because a control was changed). UpdateCard(); } protected void cmdUpdate_Click(object sender, EventArgs e) { // Refresh the greeting card (because the button was clicked). UpdateCard(); } }

Lu hnh ni b

Trang 87

BI THC HNH CHNG 2: Bi 1: Thc hnh li tt c cc th d v HTML Server Controls v Web Server Controls c hc. C th vit cc bi thc hnh c ni dung tng ng cc th d nm vng bi hc. Bi 2: S dng cc iu khin thc hin bi tp sau : To trang Default.aspx vi ni dung sau:

Khi click vo cc LinkButton 1,2,3 hoc 4 ,s chuyn n trang thc hin cc bi tp tng ng : 1. Nhp x v in ra tri tuyt i x (

2. Tnh S=1+2+3+...+n vi n s nguyn v n>=1 3. In ra cc s c 3 ch s sao cho abc=a^3+b^3+c^3.

4. Tnh Cos(x)=1-x^2/2!+x^4/4!-... vi epsilon=10^-6.

Hng dn: Ni dung trang Default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { width: 100%; } .style2 { text-align: center; font-weight: bold;

Lu hnh ni b

Trang 88

font-size: x-large; } </style> </head> <body> <form id="form1" runat="server"> <div> <table class="style1"> <tr> <td class="style2"> BI TP S DNG WEB SERVER CONTROLS</td> </tr> <tr> <td> <asp:BulletedList ID="BulletedList1" runat="server" BorderStyle="Dotted" BulletStyle="Numbered" DisplayMode="LinkButton" onclick="BulletedList1_Click"> </asp:BulletedList> </td> </tr> <tr> <td> &nbsp;</td> </tr> </table> </div> </form> </body> </html>

Phn m lnh trang Default.aspx.cs


public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BulletedList1.Items.Add("Nhp x. In ra tr tuyt i x."); BulletedList1.Items.Add("Tnh S=1+2+3+...+n vi n nguyn >=1"); BulletedList1.Items.Add("In ra cc s c 3 ch s sao cho abc=a^3+b^3+c^3."); BulletedList1.Items.Add("Tm Cos(x)=1-x^2/2!+x^4/4!-... vi epsilon=10-6"); } } protected void BulletedList1_Click(object sender, BulletedListEventArgs e) { int item = e.Index; if (item==0) Response.Redirect("TrituyetdoiX.aspx"); else if (item==1) Response.Redirect("TinhS.aspx"); else if (item==2) Response.Redirect("BaChuSo.aspx");

Lu hnh ni b

Trang 89

else Response.Redirect("Cosx.aspx"); } }

- To trang BaChuSo.aspx vi ni dung thit k sau:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="BaChuSo.aspx.cs" Inherits="BaChuSo" %> <!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 runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { width: 100%; } .style2 { font-size: large; font-weight: bold; text-align: center; } </style> </head> <body> <form id="form1" runat="server"> <div> <table class="style1"> <tr> <td class="style2"> IN CC S C 3 CH S BNG TNG LP PH NG TNG CH S</td> </tr> <tr> <td> <asp:Button ID="BtnIn3So" runat="server" onclick="BtnIn3So_Click" style="font-size: medium; font-weight: 700" Text="In s" /> </td> </tr> <tr> <td> <asp:Label ID="lblKQ" runat="server" style="text-align: center; font-weight: 700; font-size: large"></asp:Label> </td> </tr> </table> </div> </form>

Lu hnh ni b

Trang 90

</body> </html>

Phn m lnh trang BaChuSo.aspx.cs nh sau:


public partial class BaChuSo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void BtnIn3So_Click(object sender, EventArgs e) { int a, b, c; string kq = "Cac so : "; for (int i = 100; i <= 999; i++) { a = i / 100; b = (i % 100) / 10; c = i % 10; if (Math.Pow(a, 3) + Math.Pow(b, 3) + Math.Pow(c, 3) == i) kq += i.ToString() + " ,"; } lblKQ.Text = kq.Substring(0, kq.Length - 1); } }

- To trang Cosx,aspx vi ni dung thit k sau:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Cosx.aspx.cs" Inherits="Cosx" %> <!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 runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { width: 100%; } .style2 { text-align: center; font-weight: bold; font-size: large; } .style3 { font-size: large; font-weight: bold; } </style> </head> <body> <form id="form1" runat="server"> <div>

Lu hnh ni b

Trang 91

<table class="style1"> <tr> <td class="style2" colspan="3"> TNH COS(X)=1-X^2/2!+X^2/4!-.... dng vi epsilon=10^-6</td> </tr> <tr> <td> <span class="style3">&nbsp;Nhp gc x () cn tnh Cos(x)&nbsp; :</span>&nbsp;</td> <td> <asp:TextBox ID="txtX" runat="server"></asp:TextBox> </td> <td> &nbsp;</td> </tr> <tr> <td> <asp:Button ID="btnSinx" runat="server" Font-Bold="True" onclick="btnCox_Click" Text="Tnh Cos(X)" /> </td> <td> &nbsp;</td> <td> &nbsp;</td> </tr> <tr> <td colspan="3" style="font-size: large; font-weight: 700; text-align: center"> <asp:Label ID="lblKQ" runat="server"></asp:Label> </td> </tr> </table> </div> </form> </body> </html>

Phn m lnh Cosx.aspx.cs


public partial class Cosx : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (this.IsPostBack == false) txtX.Text = "0.00"; } protected void btnCox_Click(object sender, EventArgs e) { double x,p, cosx; const double esp=1e-06; int i; try { x = Double.Parse(txtX.Text)*Math.PI/180; // doi tu do sang radian cosx = 1;

Lu hnh ni b

Trang 92

p = -Math.Pow(x, 2) / 2; i = 2; while(Math.Abs(p)>=esp){ cosx+=p; p*=-Math.Pow(x,2)/((i+1)*(i+2)); i+=2; } cosx+=p; lblKQ.Text="Cos("+txtX.Text+")="+cosx; } catch(Exception ex){ } } }

Lu hnh ni b

Trang 93

Chng 3:

MASTER PAGE WEBSITE NAVIGATION

Cc vn chnh s c cp : Cu trc mt MasterPage Cc dng toMater Page Cch to SiteMap kt hp vi trang Master Cch to Web User Control. Cc i tng Request, Response v Server. Kt thc bi ny cc bn c th : Nm vng cch to Master Page v Web User Control, s dng cc i tng ASP.NET gm Request, Response v Server. 3.1 MATER PAGE Cc trang Master tng t nh cc trang ASP.NET. Ging nh cc trang thng thng, cc trang master l nhng tp tin vn bn c th cha HTML, iu khin web, v m lnh. Tuy nhin, cc trang master c phn m rng tp tin l .master thay v. aspx, v chng khng th c xem trc tip bi mt trnh duyt. Thay vo , cc trang master phi c s dng bi cc trang khc, c bit n nh l ni dung trang. V c bn, trang master xc nh cu trc trang v cc thnh phn chung. Cc trang ni dung thng qua cu trc ny v ch cn in vo n vi ni dung thch hp. Th d, nu mt trang web bn sch c to ra bng cch s dng ASP.NET, mt trang master n c th xc nh b tr cho ton b trang web. Mi trang s s dng trang master ny, v kt qu l, mi trang s c cng mt t chc c bn v tiu tng t (header,footer, v vv..). Tuy nhin, mi trang s cng chn thng tin c th ca n, chng hn nh sch bn chy, sch mi, sch gim gi, hoc kt qu tm kim, vo trong mu ny. 3.1.1 To Master Page n gin to mt Master Page trong mt ng dng web c sn, bn chn R-Click ti ng dng web trong ca s Solution Explorer v chn Add New Item.., xut hin hp thoi , bn chn Master Page nh trong hnh 3.1

Hnh 3.1 Hp thoi to Master Page Nhp tn master page vo trong khung Name : DefaultContent.master v nhp nt Add, trang DefaultContent.master s c thm vo trong ng dng, v ni dung sau : Lu hnh ni b Trang 94

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="DefaultContent.master.cs" Inherits="DefaultContent" %> <!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 runat="server"> <title>Untitled Page</title> <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder> </head> <body> <form id="form1" runat="server"> <div> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> </form> </body> </html> Bn dng u tin ca trang s bt u bng ch dn Master : <%@ Master Language="C#" AutoEventWireup="true" CodeFile="DefaultContent.master.cs" Inherits="DefaultContent" %> Chuyn qua ch hin th l Design , trn trang master va to c sn hai thnh phn l ContentPlaceHolder :

Hnh 3.2 Trang DefaultContent.master va dc thm vo ng dng ContentPlaceHolder th nht c a vo trong th Head, mang n cho cc trang ni dung cc trang thm siu d liu (meta data), chng hn nh cc t kha tm kim v lin kt trang tnh (search keywords and style sheet links) Lu hnh ni b Trang 95

<head runat="server"> <title>Untitled Page</title> <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder> </head> ContentPlaceHolder th hai c a vo trong th Body, i din cc ni dung hin th ca trang. N xut hin trn cc trang nh l mt khung rng ch sn ni dung s c in vo t trang . Nu bn nhpvo bn trong hoc di chut qua n, tn ca ContentPlaceHolder xut hin trong mt tooltip, nh trong hnh 3.3. Phn kch thc ca khung s m rng ph hp vi ni dung bn t bn trong.

Hnh 3.3 Trang DefaultContent.master cha ContentPlaceHolder bn trong th Body. Bn thay i ni dung trang DefaultContent.master nh sau : <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <img src="NhatNghe.JPG" alt="NhatNghe" /><br /> <asp:contentplaceholder id="ContentPlaceHolder1" runat="server"> This is default content.<br /> </asp:contentplaceholder> <i>This is a simple footer.</i> </div> </form> </body> </html> Lu hnh ni b Trang 96

Chuyn qua ch hin th l Design , trn trang master va thay i c ni dung sau :

Hnh 3.4 Trang DefaultContent.master sau khi cp nht ni dung. To trang DefaultContentPage.aspx s dng trang master l DefaultContent.master.

Chnh sa ni dung trang DefaultContentPage.aspx ch cn mt dng m lnh nh sau , ch thuc tnh MasterPageFile trong th ch dn Page: <%@ Page Language="C#" MasterPageFile="~/DefaultContent.master" AutoEventWireup="true" CodeFile="DefaultContentPage.aspx.cs" Inherits="DefaultContentPage_aspx" Title="Untitled Page" %> Kt qu hin th khi chuyn sang ch Design , ni dung ca trang ging nh ni dung trang master c khai bo trong n.

Hnh 3.5 Trang DefaultContentPage.aspx sau khi cp nht ni dung. - a ni dung vo trong khung ContentPlaceHolder : To thm mt trang master cho ng dng l SiteTemplate.master c ni dung sau : <%@ Master Language="C#" AutoEventWireup="true" CodeFile="SiteTemplate.master.cs" Inherits="SiteTemplate" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Lu hnh ni b Trang 97

<html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <img src="NhatNghe.jpg" alt="NhatNghe" /><br /> <asp:contentplaceholder id="ContentPlaceHolder1" runat="server"> </asp:contentplaceholder> <i>This is a simple footer.</i></div> </form> </body> </html> V to trang SimpleContentPage.aspx c MasterPageFile="~/SiteTemplate.master" , trong trang ny c a ni dung vo trong ContentPlaceHolder qua th asp:Content nh sau : <%@ Page Language="C#" MasterPageFile="~/SiteTemplate.master" AutoEventWireup="true" CodeFile="SimpleContentPage.aspx.cs" Inherits="SimpleContentPage_aspx" Title="Content Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <br /> &nbsp;&nbsp;&nbsp;&nbsp; Here's some new content!<br /> </asp:Content> Kt qu hin th ch Design , ni dung ca trang SimpleContentPage.aspx nh sau :

Hnh 3.6 Trang SimpleContentPage.aspx c ni dung hin th trong ContentPlaceHolder. Bn thy ni dung : <br /> &nbsp;&nbsp;&nbsp;&nbsp; Here's some new content!<br /> c hin th trong khung ContentPlaceHolderID="ContentPlaceHolder1" khai bo trong trang SiteTemplate.master 3.1.2 To trang Mater Page c nhiu khu vc cha ni dung Trang Master khng gii hn ch c mt ContentPlaceHolder. Tt c bn cn lm l thm nhiu iu khin ContentPlaceHolder v sp xp chng mt cch thch hp trn trang Master ny. Lu hnh ni b Trang 98

To thm mt trang master vo ng dng c tn MultipleContent.master vi ni dung sau : <%@ Master Language="C#" AutoEventWireup="true" CodeFile="MultipleContent.master.cs" Inherits="MultipleContent" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <img src="NhatNghe.JPG" alt="NhatNghe" /><br /><br /> <asp:contentplaceholder id="MainContent" runat="server"> </asp:contentplaceholder> <div style="border-right: 1px solid; padding-right: 15px; border-top: 1px solid; padding-left: 15px; font-size: small; padding-bottom: 15px; margin: 15px; border-left: 1px solid; width: 417px; padding-top: 15px; border-bottom: 1px solid; font-family: Verdana; background-color: #ffffcc"> <strong> OTHER LINKS<br /> </strong> <asp:ContentPlaceHolder id="OtherLinksContent" runat="server"> </asp:ContentPlaceHolder> </div> <i>This is a simple footer.</i> </div> </form> </body> </html> Kt qu hin th khi chuyn sang ch Design , ni dung ca trang MultipleContent.master nh sau :

Hnh 3.7 Trang MultipleContent.master c hai khung ContentPlaceHolder. Trang master ny c cha hai ContentPlaceHolder trong th Body l : <asp:contentplaceholder id="MainContent" runat="server"> Lu hnh ni b Trang 99

</asp:contentplaceholder> v <asp:ContentPlaceHolder id="OtherLinksContent" runat="server"> </asp:ContentPlaceHolder> Sau , bn to trang MultipleContentPage.aspx s dng trang MultipleContent.master trn vi ni dung sau :
<%@ Page Language="C#" MasterPageFile="~/MultipleContent.master" AutoEventWireup="true" CodeFile="MultipleContentPage.aspx.cs" Inherits="MultipleContentPage_aspx" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server"> This is the generic content for this page. Here you might provide some site specific text. This is the generic content for this page. Here you might provide some site specific text. This is the generic content for this page. Here you might provide some site specific text. This is the generic content for this page. Here you might provide some site specific text.<br /> <br /> This is the generic content for this page. Here you might provide some site specific text. This is the generic content for this page. Here you might provide some site specific text.This is the generic content for this page. Here you might provide some site specific text.</asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="OtherLinksContent" Runat="Server"> Here's a <a href="http://www.prosetech.com">link</a>. <br /> Here's a <a href="http://www.prosetech.com">link</a>.<br /> Here's a <a href="http://www.prosetech.com">link</a>.<br /> Here's a <a href="http://www.prosetech.com">link</a>.</asp:Content>

Kt qu hin th khi chuyn sang ch Design , ni dung ca trang MultipleContentPage.aspx nh sau :

Hnh 3.8 Trang MultipleContentPage.aspx c ni dung a vo cho hai khung ContentPlaceHolder. 3.1.3 To trang Master Page vi cu trc bng Phn ny hng dn cc bn to mt trang Master theo thit k bng (Table-Based Layouts). Chng ta thit k cc trang ASP.NET theo cng mt mu trang master c dng nh hnh sau : Lu hnh ni b Trang 100

Hnh 3.9 Trang Master thit k theo table layout. To trang master c tn TableMaster.master c ni dung sau : <%@ Master Language="C#" AutoEventWireup="true" CodeFile="TableMaster.master.cs" Inherits="TableMaster" %> <!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 id="Head1" runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <table width="80%"> <tr> <td colspan="2" style="background: #ffccff"> <!-- MyHeader --> <img src="NhatNghe.jpg" alt="NhatNghe" /><br /> </td> </tr> <tr> <td style="background: #ffffcc" > Lu hnh ni b Trang 101

<asp:treeview ID="Treeview1" runat="server" Width="150px"> <Nodes> <asp:TreeNode Text="Root" Value="New Node"> <asp:TreeNode Text="Page 1" Value="Page 1"></asp:TreeNode> <asp:TreeNode Text="Page 2" Value="Page 2"></asp:TreeNode> </asp:TreeNode> </Nodes> </asp:treeview> </td> <td> <asp:contentplaceholder id="ContentPlaceHolder1" runat="server"> </asp:contentplaceholder> </td> </tr> <tr> <td colspan="2" style="background: #ccff33"> <i>My Footer</i> </td> </tr> </table> </form> </body> </html> Kt qu hin th khi chuyn sang ch Design , thit k ca trang TableMaster.master nh sau :

Hnh 3.10 Trang TableMaster thit k theo table layout. Khai bo mt property ShowNavigationControls trong trang TableMaster.master.cs bt hoc tt iu khin Treeview trn trang master.
public partial class TableMaster : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { } public bool ShowNavigationControls { set { Treeview1.Visible = value; } get { return Treeview1.Visible; } } }

Sau , bn to trang TableContentPage.aspx s dng trang TableMaster.master trn vi ni dung sau :

Lu hnh ni b

Trang 102

<%@ Page Language="C#" MasterPageFile="~/TableMaster.master" AutoEventWireup="true" CodeFile="TableContentPage.aspx.cs" Inherits="TableContentPage_aspx" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> Your content goes in this cell.<br /> <br /> <asp:Button ID="cmdShow" runat="server" Text="Show" OnClick="cmdShow_Click" /> <asp:Button ID="cmdHide" runat="server" Text="Hide" OnClick="cmdHide_Click" /> </asp:Content>

Kt qu hin th khi chuyn sang ch Design , ni dung ca trang TableContentPage.aspx nh sau :

Vit phn m lnh thc thi trong trang TableContentPage.aspx.cs :


public partial class TableContentPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } // Khi click nt Hide , che iu khin Treeview trn trang master protected void cmdHide_Click(object sender, EventArgs e) { TableMaster master = (TableMaster)this.Master; master.ShowNavigationControls = false; } // Khi click nt Show, hin th iu khin Treeview trn trang master protected void cmdShow_Click(object sender, EventArgs e) { TableMaster master = (TableMaster)this.Master; master.ShowNavigationControls = true; } }

Thc thi trang TableContentPage.aspx, ta c kt qu :

Hnh 3.11 Thc thi trang TableContentPage (click nt Show).

Lu hnh ni b

Trang 103

Hnh 3.11 Thc thi trang TableContentPage (click nt Hide). 3.2 WEBSITE NAVIGATION Bn hc c cch n gin cho mt ngi truy cp trang web t trang ny sang trang khc. Th d, bn c th thm cc lin kt HTML (hoc iu khin HyperLink) trong trang ca bn cho php ngi dng lt web thng qua trang web ca bn. Nu bn mun thc hin chuyn hng trang, bn c th gi Response.Redirect() hoc Server.Transfer() trong trang m lnh ca bn. Nhng trong ng dng web chuyn nghip, cc yu cu chuyn hng chuyn su hn. Cc ng dng ny cn mt h thng cho php ngi dng lt web thng qua mt h thng cc trang, m khng buc bn vit on code chuyn hng cng bun t trong mi trang. ASP.NET cung cp mt m hnh chuyn hng d dng cho php ngi dng lt web thng qua cc ng dng web ca bn. Trc khi bn c th s dng m hnh ny, bn cn phi xc nh h thng cp bc ca trang web ca bn, ni cch khc, lm th no cc trang c t chc thnh cc nhm mt cch logic. Bn sau xc nh rng cu trc trong mt tp tin chuyn dng v kt ni thng tin chuyn hng vi cc iu khin menu bao gm TreeView v Menu.

Hnh 3.12 ASP.NET navigation vi SiteMap. 3.2.1 Site Maps Thc hin vic to mt Website SimpleSiteMap: Lu hnh ni b Trang 104

Trong to trang Web.sitemap, bn R-Click ti tn Project trong ca s Solution Explorer, Click mc Add New Item.., xut hin hp thoi Add New Item, chn mc Site Map trong hnh v click nt Add :

Hnh 3.13 To trang Web.sitemap vi mc chn SiteMap. Ni dung trang Web.sitemap ban u nh sau : <?xml version="1.0" encoding="utf-8" ?> <siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > <siteMapNode url="" title="" description=""> <siteMapNode url="" title="" description="" /> <siteMapNode url="" title="" description="" /> </siteMapNode> </siteMap> Cc nguyn tc to trang SiteMap: - Nguyn tc 1 : Mt trang SiteMap bt u bng th <siteMap> <siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > . </siteMap> - Nguyn tc 2 : Mi trang web trong SiteMap c khai bo trong th <siteMapNode> <siteMapNode title="RevoStock" description="Investment software for stock charting" url="~/product1.aspx" /> Nguyn tc 3 : Mt siteMapNode c th cha cc siteMapNode khc.

<siteMapNode title="Products" description="Learn about our products" url="~/products.aspx"> <siteMapNode title="RevoStock" description="Investment software for stock charting" url="~/product1.aspx" /> <siteMapNode title="RevoAnalyze" description="Investment software for yield analysis" url="~/product2.aspx" /> </siteMapNode> - Nguyn tc 4 : Lp li a ch URL trong cc siteMapNode l khng cho php. Lu hnh ni b Trang 105

Cc bn thit k trang sitemap vi ni dung sau : <?xml version="1.0" encoding="utf-8" ?> <siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0"> <siteMapNode title="Home" description="Home" url="~/default.aspx"> <siteMapNode title="Information" description="Learn about our company"> <siteMapNode title="About Us" description="How RevoTech was founded" url="~/aboutus.aspx" /> <siteMapNode title="Investing" description="Financial reports and investor analysis" url="~/financial.aspx" /> </siteMapNode> <siteMapNode title="Products" description="Learn about our products" url="~/products.aspx"> <siteMapNode title="RevoStock" description="Investment software for stock charting" url="~/product1.aspx" /> <siteMapNode title="RevoAnalyze" description="Investment software for yield analysis" url="~/product2.aspx" /> </siteMapNode> </siteMapNode> </siteMap> To tip trang MasterPage.master c ni dung sau : <%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Navigation Test</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <table> <tr> <td style="width: 228px;vertical-align: top;"> <asp:SiteMapPath ID="SiteMapPath1" runat="server" Width="264px" FontSize="10pt"> <PathSeparatorTemplate> <asp:Image ID="Image1" ImageUrl="~/arrowright.gif" runat="server" /> </PathSeparatorTemplate> <RootNodeTemplate> <b>Root</b> </RootNodeTemplate> <CurrentNodeTemplate> Lu hnh ni b Trang 106

<%# Eval("title") %> <br /><small><i>&nbsp;<%# Eval("description") %></i></small> </CurrentNodeTemplate> </asp:SiteMapPath> <br /> <asp:TreeView ID="TreeView1" runat="server" DataSourceID="SiteMapDataSource1" ImageSet="Faq" NodeIndent="0" > <ParentNodeStyle Font-Bold="False" /> <HoverNodeStyle Font-Underline="True" ForeColor="Purple" /> <SelectedNodeStyle Font-Underline="True" /> <NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="DarkBlue" HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" /> </asp:TreeView> </td> <td style="vertical-align: top; padding: 10px; width: 301px;" bgcolor="LightGoldenrodYellow"> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server" /> </td> </tr> </table> <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" /> </form> </body> </html> Phn thit k trang MasterPage nh sau : iu khin SitemapDataSource : <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />

iu khin SiteMapPath : <asp:SiteMapPath ID="SiteMapPath1" runat="server" Width="264px" FontSize="10pt"> <PathSeparatorTemplate> <asp:Image ID="Image1" ImageUrl="~/arrowright.gif" runat="server" /> </PathSeparatorTemplate> <RootNodeTemplate> <b>Root</b> </RootNodeTemplate> <CurrentNodeTemplate> <%# Eval("title") %> <br /><small><i>&nbsp;<%# Eval("description") %></i></small> </CurrentNodeTemplate> </asp:SiteMapPath>

Lu hnh ni b

Trang 107

Chn mc Auto Format.., chn mt la chn scheme thch hp trong danh sch v click OK.

Hnh 3.14 Thay i nh dng ca SiteMappath. Sau , bn chn mc Edit Templates thit k ni dung cho SiteMapPath : c 4 thnh phn th bn trong gm RootNodeTemplate, NodeTemplate, CurrentNodeTemplate, v PathSeparatorTemplate. Nhp ni dung th Current NodeTemplate hin th ni dung th title v th description. Trong <%# Eval("title") %> l mt cch vit theo dng kt ni d liu n gin (simple data binding) s c hc trong bi hc sau, dng ly ni dung title.
<CurrentNodeTemplate> <%# Eval("title") %> <br /><small><i>&nbsp;<%# Eval("description") %></i></small> </CurrentNodeTemplate>

Nhp ni dung th RootNodeTemplate : Hin th ch Root in m


<RootNodeTemplate> <b>Root</b> </RootNodeTemplate>

<PathSeparatorTemplate> <asp:Image ID="Image1" ImageUrl="~/arrowright.gif" runat="server" /> </PathSeparatorTemplate>

Lu hnh ni b

Trang 108

Kt qu: khi chn mc Investing , ni dung SiteMappath hin ra nh sau :

Hnh 3.15 Ni dung SiteMapPath hin th theo Web.sitemap. iu khin TreeView :

u tin chn thuc tnh DataSource ca TreeView ch n SiteMapDataSource1 , sau click vo mc Refresh Schema , ni dung TreeView s c cp nht theo SiteMapDataSource1. Click vo mc Auto Format.. nh dng hin th cho TreeView, click nt Apply xc nhn vic thay i dng hin th :

Hnh 3.16 nh dng hin th cho TreeView. Ni dng TreeView sau khi cu hnh : Lu hnh ni b Trang 109

<asp:TreeView ID="TreeView1" runat="server" DataSourceID="SiteMapDataSource1" ImageSet="Faq" NodeIndent="0" > <ParentNodeStyle Font-Bold="False" /> <HoverNodeStyle Font-Underline="True" ForeColor="Purple" /> <SelectedNodeStyle Font-Underline="True" /> <NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="DarkBlue" HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" /> </asp:TreeView>

To mt trang StyleSheet.css nh dng hin th cho cc th HTML :


body { font-family: Verdana; font-size: 83%;} div.Box { padding: 5px; border-width: 2px; border-style: ridge; background-color: Lime; }

Cc trang thnh phn trong Web.sitemap, ch thit k vi ni dung n gin minh ho cho bi tp v s c gi khi c la chn trn TreeView theo s iu hng ca Web.sitemap Trang financial.aspx
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="financial.aspx.cs" Inherits="financial" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> Investing </asp:Content>

Kt qu chn Investing trn TreeView s gi trang financial.aspx :

Hnh 3.17 Chn mc Investing trn TreeView. Tng t vi th d trn c s dng Menu trn MasterPage c iu hng theo Web.sitemap Lu hnh ni b Trang 110

Hnh 3.18 Menu s dng theo iu hng ca Web.sitemap. Chn Auto Format.. nh dng hin th cho Menu, click nt OK xc nhn vic thay i.

Hnh 3.19 nh dng hin th cho Menu. Trang MasterPage.master c cha th <asp:Menu..> c thit k theo hnh di y :

Hnh 3.20 Menu theo iu hng ca Web.sitemap. Ni dung trang MasterPage.master nh sau: <%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Navigation Test</title> Lu hnh ni b Trang 111

<link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <table> <tr> <td style="width: 131px;vertical-align: top;"> <asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" BackColor="#F7F6F3" DynamicHorizontalOffset="2" Font-Names="Verdana" ForeColor="#7C6F57" StaticDisplayLevels="2" StaticSubMenuIndent="10px"> <StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" /> <DynamicHoverStyle BackColor="#7C6F57" ForeColor="White" /> <DynamicMenuStyle BackColor="#F7F6F3" /> <StaticSelectedStyle BackColor="#F7F6F3" /> <DynamicSelectedStyle BackColor="#5D7B9D" /> <DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" /> <StaticHoverStyle BackColor="#7C6F57" ForeColor="White" /> <StaticItemTemplate> <%# Eval("Text") %><br /> <small> <%# GetDescriptionFromTitle(((MenuItem)Container.DataItem).Text) %> </small> </StaticItemTemplate> <DynamicItemTemplate> <%# Eval("Text") %><br /> <small> <%# GetDescriptionFromTitle(((MenuItem)Container.DataItem).Text) %> </small> </DynamicItemTemplate> </asp:Menu> </td> <td style="vertical-align: top; padding: 10px" > <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server" /> </td> </tr> </table> <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" /> </form> </body> </html> Phn m lnh ca trang MasterPage.master cung cp phng thc GetDescriptionFromTitle(string Title) hin thng tin th chn trn menu. public partial class MasterPage : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { Lu hnh ni b Trang 112

} protected string GetDescriptionFromTitle(string title) { // This assumes there's only one node with this title. SiteMapNode startingNode = SiteMap.RootNode; SiteMapNode matchNode = SearchNodes(startingNode, title); if (matchNode == null) { return null; } else { return matchNode.Description; } } private SiteMapNode SearchNodes(SiteMapNode node, string title) { if (node.Title == title) { return node; } else { // Perform recursive search. foreach (SiteMapNode child in node.ChildNodes) { SiteMapNode matchNode = SearchNodes(child, title); // Was a match found? // If so, return it. if (matchNode != null) return matchNode; } // All the nodes were examined, but no match was found. return null; } } } 3.3 WEB USER CONTROLS 3.3.1 Gii thiu User Custom Control MS Visual Studio .NET cung cp rt nhiu cc iu khin pht trin ng dng gi l iu khin ni ti (Instrict control). Ngoi ra, n cn cung cp cho chng ta kh nng t xy dng cc iu khin ty bin, nu cc iu khin hin hnh khng p ng c yu cu thit k trang web vi nhng chc nng ring bit. Th d: Nu ng dng ca bn cn chic my tnh (Calculator) rt nhiu trang th gii php tt nht l nn to mt iu khin Calculator ring thay vic kt hp cc iu khin truyn thng, khi ta c th s dng iu khin ny trong ton b ng dng. mc ny s hng dn cch to v s dng iu khin do ngi dng t xy dng Lu hnh ni b Trang 113

hay cn gi l iu khin ty bin (Web User Controls). Thc cht ca User Control (UC) chnh l mt "trang con", trong c th cha bt k ni dung no (tr cc th <HTML> <BODY>,<FORM>, v mt trang ch c duy nht mt ln xut hin cc th ny) . "Trang con" ny sau c th c khai bo vo cc trang khc s dng. Khi mun cp nht ni dung tt c cc trang, ta ch vic sa i duy nht UC ban u. Kh nng ny ca ASP.NET gip chng ta xy dng ng dng nhanh hn, d bo tr hn. Mi mt UC c t trong mt trang c phn m rng l *.ascx. File ny c c im l khng truy cp trc tip t trnh duyt m ch c chn vo cc trang aspx. Ni dung trang User Control c khai bo vi th <%@ Control ..%> nh sau : <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits=" WebUserControl " %> Phn m lnh trang WebUserControl.aspx.cs: 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; public partial class WebUserControl: System.Web.UI.UserControl { } Cc lp User Control k tha t System.Web.UI.UserControl, hnh 3.21 cho thy s tha k ca hai i tng Page (trang .aspx) v User Control (trang .ascx).

Hnh 3.21 Cy tha k ca hai i tng Page v User Control. Lu hnh ni b Trang 114

3.3.2 Cc bc to User Custom control Gm 3 bc sau : Bc 1: R-Click ti ng dng web trong ca s Solution Explorer v chn Add New Item.., xut hin hp thoi , bn chn Web User Control, nhp tn User Control vo khung Name, th d tn CalculatorControl.ascx , click nt Add, trang User Control s c thm vo ng dng.

Hnh 3.22 Menu theo iu hng ca Web.sitemap. Bc 2: Son ni dung ca trang. Bc 3: Lu li ni dung ca trang. 3.3.3 Cc loi User Control : C hai loi User Control: User Control hot ng c lp v tch hp. User Control c lp (Independent User Control) l loi iu khin khng tng tc vi phn cn li ca cc m lnh trn trang web v ngc li nu c s tng tc s la User Control tch hp (Integrated User Control). Th d 1: To User Control c lp n gin. To mt trang Footer. ascx vi ni dung hin th sau :

Bc 1: To trang Footer.ascx , v thit k ni dung trang nh sau <%@ Control Language="C#" AutoEventWireup="true" CodeFile="Footer.ascx.cs" Inherits="Footer" %> <div id="footer" class="clearfix"> <p class="col1 style2"> Lu hnh ni b Trang 115

<strong>TRUNG TM O TO MNG MY TNH NHT NGH</strong> <br/> <strong>a ch:</strong> 105 B Huyn Thanh Quan, Qun 3, TP. HCM <br/> <strong>in thoi: </strong><span class="style3">(08) 3 9322 735 - (08) 3 9322734</span><br> <strong>Email:</strong> <a href="mailto:info@nhatnghe.com">info@nhatnghe.com</a> <br/> <strong>Website:</strong> <a href="http://www.nhatnghe.com">http://www.nhatnghe.com</a></p> </div> <asp:Label id="lblFooter" runat="server" /> iu khin nhn lblFooter s hin th ni dung ngy hoc gi khi trang web c s dng User Control Footer trn c triu gi. Thit k ni dung m lnh cho trang nh sau: public partial class Footer : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { lblFooter.Text= "<br/> Trang ny c triu gi lc "; if (format == FooterFormat.LongDate) { lblFooter.Text += DateTime.Now.ToLongDateString(); } else if (format == FooterFormat.ShortTime) { lblFooter.Text += DateTime.Now.ToShortTimeString(); } } public enum FooterFormat { LongDate, ShortTime } private FooterFormat format = FooterFormat.LongDate; public FooterFormat Format { get { return format; } set { format = value; } } } To trang FooterHost.aspx c s dng User Control- Footer trn bng cch khai bo th <%@ Register.. %> c dng sau :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FooterHost.aspx.cs" Inherits="FooterHost" %> <%@ Register TagPrefix="uc" TagName="Footer" Src="Footer.ascx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" >

Lu hnh ni b

Trang 116

<head runat="server"> <title>Footer Host</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <h2>A Page With a Configurable Footer</h2> <br /><br /><br /> <hr /> <asp:RadioButton id="optShort" runat="server" GroupName="Format" Text="Short Format"></asp:RadioButton> <br /> <asp:RadioButton id="optLong" runat="server" GroupName="Format" Text="Long Format"></asp:RadioButton> <br /><br /> <asp:Button id="cmdRefresh" runat="server" Text="Refresh"></asp:Button> <hr /> <br /> <uc:Footer id="Footer1" runat="server"></uc:Footer> </div> </form> </body> </html>

Kt qu thc thi :

Th d 2: To User Control tch hp To mt User Control vi tn LinkMenu.ascx c ni dung thit k nh sau : <%@ Control Language="C#" AutoEventWireup="true" CodeFile="LinkMenu2.ascx.cs" Inherits="LinkMenu2" %> Lu hnh ni b Trang 117

<div style="border-right: 2px groove; padding-right: 5px; border-top: 2px groove; padding-left: 5px; font-weight: bold; font-size: small; padding-bottom: 5px; border-left: 2px groove; width: 100px; padding-top: 5px; border-bottom: 2px groove; font-family: Verdana; height: 120px; background-color: #FFFFD9"> Products: <asp:LinkButton ID="lnkBooks" runat="server" CommandArgument="Menu2Host.aspx?product=Books" OnCommand="lnk_Command" >Books </asp:LinkButton><br /> <asp:LinkButton ID="lnkToys" runat="server" CommandArgument="Menu2Host.aspx?product=Toys" OnCommand="lnk_Command">Toys </asp:LinkButton><br /> <asp:LinkButton ID="lnkSports" runat="server" CommandArgument="Menu2Host.aspx?product=Sports" OnCommand="lnk_Command">Sports </asp:LinkButton><br /> <asp:LinkButton ID="lnkFurniture" runat="server" CommandArgument="Menu2Host.aspx?product=Furniture" OnCommand="lnk_Command">Furniture </asp:LinkButton> </div>

Khi click ti LinkButton Books c khai bo cc thuc tnh ca iu khin lnkBooks vi OnCommand="lnk_Command" v CommandArgument="Menu2Host.aspx?product=Books" cho php chuyn n trang Menu2Host.aspx vi chui (query string) ni dung l product=Books tng t lnh Response.Redirect(). Products: <asp:LinkButton ID="lnkBooks" runat="server" CommandArgument="Menu2Host.aspx?product=Books" OnCommand="lnk_Command" >Books </asp:LinkButton><br /> Ni dung trang m lnh c khai bo phng thc lnk_Command(object sender, CommandEventArgs e) c cu trc khai bo ging nh khai bo hnh thc ca mt hm u thc (delegate) : public delegate void LinkClickedEventHandler(object sender, LinkClickedEventArgs e); Lu hnh ni b Trang 118

p ng s kin LinkClicked xy ra khi click trn mt LinkButton no trn trang: public event LinkClickedEventHandler LinkClicked; Nh vy, User Control LinkMenu2 gn vo mt s kin LinkClicked, v khi s kin c xy ra trn LinkButton th hm u thc ch nh thc thi s c triu gi : <asp:LinkButton ID="lnkBooks" runat="server" CommandArgument="Menu2Host.aspx?product=Books" OnCommand="lnk_Command" >Books </asp:LinkButton> Ni dung phn m lnh trang LinkMenu2.ascx.cs nh sau:
public partial class LinkMenu2 : System.Web.UI.UserControl { public event LinkClickedEventHandler LinkClicked; protected void lnk_Command(object sender, CommandEventArgs e) { // One of the LinkButton controls has been clicked. // Raise an event to the page. if (LinkClicked != null) { // Pass along the link information. LinkClickedEventArgs args = new LinkClickedEventArgs((string)e.CommandArgument); LinkClicked(this, args); // Perform the redirect. if (!args.Cancel) { // Notice we use the Url from the LinkClickedEventArgs // object, not the original link. That means the web page // can change the link if desired before the redirect. Response.Redirect(args.Url); } } } }

Ni dung trang xy dng lp s kin LinkClickedEventArgs, cha mt property Url trong khai bo constructor ca lp.
public class LinkClickedEventArgs : EventArgs { private string url; public string Url { get { return url; } set { url = value; } } private bool cancel = false; public bool Cancel { get { return cancel; }

Lu hnh ni b

Trang 119

set { cancel = value; } } public LinkClickedEventArgs(string url) { Url = url; } } public delegate void LinkClickedEventHandler(object sender, LinkClickedEventArgs e);

To trang Menu2Host.aspx c s dng User Control LinkMenu2 va thit k trn:

Ni dung trang nh sau:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Menu2Host.aspx.cs" Inherits="Menu2Host"%> <%@ Register TagPrefix="uc" TagName="LinkMenu2" Src="LinkMenu2.ascx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Menu Host</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <table> <tr> <td style="width: 100px"> <uc:LinkMenu2 id="Menu1" runat="server" OnLinkClicked="LinkClicked" /> </td> <td> &nbsp;&nbsp;<asp:Label id="lblSelection" runat="server" EnableViewState="false"/><br /> &nbsp;&nbsp;<asp:Label id="lblClick" runat="server" EnableViewState="false"/> </td> </tr> </table> <br /> &nbsp;

Lu hnh ni b

Trang 120

</div> </form> </body> </html>

Ni dung trang m lnh Menu2Host.aspx.cs c vit hm u thc LinkClicked(object sender, LinkClickedEventArgs e) c gi khi s kin LinkClicked xy ra trn uc:LinkMenu2:
public partial class Menu2Host : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Request.Params["product"] != null) { lblSelection.Text = "You chose: "; lblSelection.Text += Request.Params["product"]; } } } protected void LinkClicked(object sender, LinkClickedEventArgs e) { if (e.Url == "Menu2Host.aspx?product=Furniture") { lblClick.Text = "This link is not allowed."; e.Cancel = true; } else { // Allow the redirect, and don't make any changes to the URL. } } }

Kt qu thc thi:

Lu hnh ni b

Trang 121

Khi click ln LinkButton Furniture , thng bo s hin ra tng ng ni dung trong hm u thc, lc ny khng c thc hin vic chuyn trang.
if (e.Url == "Menu2Host.aspx?product=Furniture") { lblClick.Text = "This link is not allowed."; e.Cancel = true; }

Kt qu:

3.4 CC I TNG REQUEST, RESPONSE V SERVER thc hin vic giao tip (truyn d liu) gia cc webform ASP.NET cung cp mt tp cc iu khin gip ta lm vic mt cch d dng, l: i tng Request v i tng Response. Trong phn ny, chng ta cng tm hiu thm mt i tng khc cng rt hay dng khi xy dng ng dng l i tng Server.
Http Request
Resource

Web Server

Http Response

Web Client (Browse)

Hnh 3.23: Qu trnh Request Response ca HTTP i tng Request i tng Request c dng nhn nhng thng tin t trnh duyt ca ngi dng gi v cho Web Server. Nhng thng tin ny gm cc thng s ca Form khi c Submit dng phng thc POST hoc GET hay cc tham s c ghi cng vi trang ASP.NET trong li gi n trang . Lu hnh ni b Trang 122

Dng i tng Request c th chia s thng tin qua li gia cc trang ASP.NET trong mt ng dng v ly gi tr cc Cookie lu tr trn my Client. Bng thuc tnh v phng thc ca Request Phng thc / Din gii thuc tnh Tr v mng chui ca MIME c h tr bng trnh AccepTypes khch Tr v ng dn o ca ng dng ApplicationPath Tr v mng Byte cha ng thng tin nh phn gi n BinayRead Server Tr v i tng HttpBrowserCapabilities trnh by Browser thng tin ca trnh duyt ClientCertificate Tr v i tng HttpClientCertificate ContentEncoding Tp k t ca thc th Body Chiu di tnh bng byte ca yu cu ContentLength Loi MILE ca yu cu ContentType Tr v i tng HttpCookiesCollection Cookies Tr v ng dn o ca yu cu Filepath Tr v HttpFileCollection ca tp nhiu tp tin c ti Files ln Server Tr v tp d liu ca ni dung t Form Form Tr v tp d liu ca ni dung t HTTP Header Header Tr v phng thc HTTP s dng cho yu cu HttpMethod L lung d liu cha ng cc Input ca Form InputStream Ly gi tr ca phng thc trong Form, QueryString Params ng dn o ca yu cu Path ng dn o ca yu cu PathInfo ng dn vt l ca yu cu PhysicalPath Tr v mt tp d liu ca ni dung t QueryString QueryString URL ca yu cu RawURL Phng thc HTTP s dng cho Resquest RequestType Dung lng ca Stream trong lung d liu TotalByte i tng URL cha ng chi tit ca yu cu URL Tn DNS ca ngi s dng UserHostName Chuyn i ng dn o thnh ng dn vt l MapPath Lu yu cu HTTP vo a SaveAs C 2 cch gi thng tin c bit t trnh duyt n Web server, l thng tin t phn <FORM> trong trang c a vo HTTP header hay c a trc tip vo chui truy vn trong a ch lin kt URL. chnh l vai tr ca 2 tp hp QueryString v Form ca i tng Request. Tp hp QueryString: ly c gi tr t chui truy vn ta dng: Request.QueryString (tn bin). Khi thuc tnh ca <FORM> phi c dung l METHOD = GET Tp hp Form: ly c gi tr t t phn Header ca HTTP ta dng: Lu hnh ni b Trang 123

Request.QueryString (tn bin). Khi thuc tnh ca <FORM> phi c dung l METHOD = POST So snh gia hai tp hp Form v QueryString: Theo phng php dng QueryString c hn ch l gii hn chiu di ca chui a ch URL (khong 1000 k t) y chnh l yu cu ca giao thc HTTP. Do s rt phin phc khi c yu cu gi i qu di. Mc khc, gi tr m ta gi i c hin th r rng trong a ch URL trn trnh duyt my Client nn d dng b ngi khc c c. Phng php dng POST khc phc c nhc im trn bng cch a d liu vo trong phn Header ca HTTP. i tng Response Trong h thng cc i tng xy dng sn ca ASP.NET th i tng Response ng vai tr rt quan trng. Khi m i tng Request bao gm nhng thng tin gi n Web server t trnh duyt th i tng Response nm gi nhng g m Web server phi gi tr li cho trnh duyt. Tm li, ta dng i tng Response gi thng tin ra User, gm c ghi thng tin trc tip ra Browser, chuyn Browser n a ch URL khc hay thit lp cc Cookie trn my Client. Bng cc thuc tnh v phng thc ca i tng Response Thuc tnh / phng thc BufferOutput Cache CacheControl ContentEncoding Cookies Expries ExpriesAbsolute Filter Output OutputStream Status StatusCode StatusDescription ClearContent ClearHeaders Close Redirect Writeln Write Lu hnh ni b Din gii C s dng hay khng b nh m cho kt xut d liu Tr v i tng HttpCachePolicy cha ng thng tin v quy nh Cache ca phc p hin hnh Mc d cn h tr nhng phng thc ny cn i nghch trong phng thc ca HttpCachePolicy Tp nhn dng kt xut, l mt trong cc gi tr nh UnicodeEncoding, UTF7Encoding, UTF8Encoding Tr v mt tp ca i tng HttpCookies Mc d cn h tr nhng phng thc ny cn i nghch trong phng thc ca HttpCachePolicy Mc d cn h tr nhng phng thc ny cn i nghch trong phng thc ca HttpCachePolicy i tng Stream dng lm b lc d liu kt xut Tr v i tng TextWriter i tng Stream dng trnh by hng d liu ca body Gn trng thi HTTP tr v cho trnh khch Trng thi HTTP Response Gn din gii trng thi HTTP v tr v cho trnh khch, thuc tnh ny c u tin hn thuc tnh Status Xa ni dung t Buffer Stream Xa header t Buffer Stream ng kt ni vi Client Chuyn hng n a ch file trong cng ng dng hay URL khc trong lc thi hnh Ghi mt lung d liu ra tp tin ch nh Ghi thng tin t cc kiu d liu nh Char, Object, String, Trang 124

Array ra trang web Th d : Minh ha s dng i tng Request v Response Bc 1 :To 2 trang ASP.NET gm trang NhapTen.aspx v trang XemChiTiet.aspx. Bng m t cc thuc tnh ca cc controls trang NhapTen.aspx. Control Lable Lable TextBox TextBox Button Tn thuc tnh Text Text ID ID Text ID Gi tr thuc tnh Nhp tn Ngy Sinh txtTen txtNgaySinh Xem chi tit btnXemChiTiet

Bng m t cc thuc tnh ca cc controls trang XemChiTiet.aspx. Control Lable Tn thuc tnh ID Gi tr thuc tnh lblXemChiTiet

Bc 2 : Vit lnh x l cho cc trang nh sau :


public partial class NhapTen : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnXemChiTiet_Click(object sender, EventArgs e) { //Ly cc gi tr nhp vo cc TextBox string strHoTen = txtTen.Text; string strNgaySinh = txtNgaySinh.Text; //Chuyn quan trang XemChiTiet.aspx Response.Redirect("XemChiTiet.aspx?Ten="+strHoTen+"&NgaySinh="+strNgaySinh ); } }

Minh ha phn m ca trang NhapTen.aspx


public partial class XemChiTiet : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Ly cc gi tr t trang NhapTen.aspx string strHoTen = Request.QueryString["Ten"]; string strNgaySinh = Request.QueryString["NgaySinh"]; lblXemChiTiet.Text = "Xin cho bn :"+strHoTen+"<br>"+ "Ngy sinh ca bn l :"+strNgaySinh; } }

Minh ha phn m ca trang XemChiTiet.aspx

Lu hnh ni b

Trang 125

Bc 3: Nhn Ctrl+F5 thi hnh ng dng. Nhp tn v ngy sinh v nhn nt Xem chi tit Kt qa nh hnh 6.2 v 6.3 .

Hnh 3.24: Khi thi hnh trang XemChiTiet.aspx

Hnh 3.25: Khi thi hnh trang XemChiTiet.aspx V d: To trang LayThongTinTrinhDuyet.aspx hin th cc thng tin cc trnh duyt ca ngi dng. Vit lnh x l nh sau : public partial class LayThongTinTrinhDuyet : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write("Browser:" + Request.Browser.Browser+"<br>"); Response.Write("Version:" + Request.Browser.Version + "<br>"); Response.Write("Platform:" + Request.Browser.Platform + "<br>"); Response.Write("JavaScript:" + Request.Browser.JavaScript); } } Lu hnh ni b Trang 126

Hnh 3.26: Kt qu thi hnh trang LayThongTinTrinhDuyet.aspx i tng Server i tng Server c s dng cung cp thng tin ca Server cho ng dng. Thuc tnh MachineName Thuc tnh ny c dng ly tn ca Web Server. Phng thc MapPath Phng thc Mappath c dng ly ng dn vt l hoc ng dn o n mt th mc trn Server. Phng thc Transfer(<ng dn n trang cn yu cu>) Ngng thi hnh trang hin hnh, gi yu cu mi n trang c gi thc hin. Th d : To trang LietKeCacBienServer , ly danh sch cc bin server
public partial class LietKeCacBienServer : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int i, j; NameValueCollection coll = Request.ServerVariables; String[] arr1 = coll.AllKeys; for (i = 0; i < arr1.Length; i++) { Response.Write("Key: " + arr1[i] + "<br>"); String[] arr2 = coll.GetValues(arr1[i]); for (j = 0; j < arr2.Length; j++) { Response.Write("Value " + j + ": " + Server.HtmlEncode(arr2[j]) + "<br>"); } } } }

Lu hnh ni b

Trang 127

Th d : Minh ha upload tp tin v Sever Ni dung trang GuiTapTin.aspx, cho php gi mt tp tin t Client n Server.

Phn m lnh:

Lu hnh ni b

Trang 128

public partial class GuiTapTin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnGui_Click(object sender, EventArgs e) { //Kim tra c tp tin no c chn ? if (fuDuLieu.HasFile) { //thit lp ng dn cho tp tin string filename = "~/DuLieu/" + fuDuLieu.FileName; //Ly ng dn vt l cho tp tin trn ng dng string s = Server.MapPath(filename); //Lu tp tin v th mc DuLieu ca ng dng fuDuLieu.SaveAs(s); Response.Write("Tp tin :"+fuDuLieu.FileName+" gi thnh cng ."); } } }

Kt qu thc thi :

Lu hnh ni b

Trang 129

Bc 5 : Kim tra kt qu . Nhp vo biu tng Show All Files trn ca s Solution , sau nhp biu tng Refresh thy kt qu nh hnh bn hoc cc bn c th kim tra bng cch m th mc DuLieu trn a xem kt qu .

Lu hnh ni b

Trang 130

BI THC HNH CHNG 3: Bi 1: Thc hin li cc bi tp th d trong chng 3. Bi 2: To mt Web User Control Login nh sau:

M lnh trang Login.ascx


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Login.ascx.cs" Inherits="Login" %> <style type="text/css"> .style1 { width: 174px; } .style2 { width: 48%; } </style> <table runat="server" id="NoiDungLogin" style="border:solid 1px purple;border-collapse:collapse; width: 307px;"> <tr> <td colspan="2" style="text-align:center; background-color:purple;color:White"> ng nhp </td> </tr> <tr> <td style="text-align:center;" class="style2">User name:</td> <td class="style1"> <asp:TextBox runat="server" ID="txtUserID" Width="79%"></asp:TextBox> </td> </tr> <tr> <td style="text-align:center; " class="style2">Password:</td> <td class="style1"> <asp:TextBox runat="server" ID="txtPassword" Width="78%" TextMode="Password"></asp:TextBox> </td> </tr> <tr> <td class="style2"> <asp:Button runat="server" ID="cmdLogin" Text="Login" /> <asp:Button runat="server" ID="cmdCancel" Text="Cancel" /> </td> <td class="style1"> &nbsp;</td> </tr> </table>

Lu hnh ni b

Trang 131

Sau , thm vo trong phn m lnh


public partial class Login : System.Web.UI.UserControl { private string dorong; public string DoRong { set { dorong = value; NoiDungLogin.Width = dorong; } get { return dorong; } } public Boolean CheckAccount() { return (txtUserID.Text == "asp.net" && txtPassword.Text == "123456"); } // Ly User name trong User name public string GetUserName() { return txtUserID.Text; } // ly Password trong Password public string GetPassword() { return txtPassword.Text; } protected void Page_Load(object sender, EventArgs e) { } }

To trang LoginDemo.aspx, s dng Web User Control Login trn


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LoginDemo.aspx.cs" Inherits="LoginDemo" %> <%@ Register src="Login.ascx" tagname="Login" tagprefix="uc1" %> <!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 runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <uc1:Login ID="Login1" runat="server" DoRong="350px" /> <br /> <asp:Label runat="server" ID="lblThongBao"></asp:Label> </div>

Lu hnh ni b

Trang 132

</form> </body> </html>

Phn m lnh thc thi trang LoginDemo.aspx.cs


public partial class LoginDemo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (this.IsPostBack == true) ///Nu khng phi ln u np trang { lblThongBao.Text = "Bn nhp User name=" + Login1.GetUserName() + " Mt khu : " + Login1.GetPassword(); } } }

Thc thi ng dng ta c kt qu:

Bi 3: To phn Menu nh sau :

Bi 4: To phn Header v Footer c th chn vo cc trang. Giao din nh sau:

Ni dung ca iu khin Header.ascx

Lu hnh ni b

Trang 133

Ni dung ca iu khin Footer.ascx Bi 5: Thit k trang MasterPage c s dng cc Web User Controls trn tao trang.

Bi 6: To mt ng dng ASP.NET thc hnh vi i tng Request v Response. To trang RequestFormGetPage.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RequestFormGetPage.aspx.cs" Inherits="RequestFormGetPage" %> <!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 runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <div> <table style="width: 292px"> <tr> <td colspan="2"> <asp:Label ID="Label1" runat="server" Font-Bold="True" Text="Quick Create New User" Width="404px"></asp:Label></td> </tr> <tr> <td style="width: 79px; height: 26px;"> <asp:Literal ID="Literal1" runat="server" Text="Email:"></asp:Literal> </td>

Lu hnh ni b

Trang 134

<td style="width: 351px; height: 26px;"> <input id="Email" runat="server" style="width: 183px" type="text" /></td> </tr> <tr> <td style="width: 79px; height: 21px"> <asp:Literal ID="Literal2" runat="server" Text="Password:"></asp:Literal></td> <td style="height: 21px; width: 351px;"> <input id="Password" runat="server" style="width: 181px" type="password" /></td> </tr> <tr> <td style="width: 79px; height: 21px"> <asp:Literal ID="Literal3" runat="server" Text="Address:"></asp:Literal></td> <td style="height: 21px; width: 351px;"> <textarea id="Address" runat="server" rows="2" style="width: 181px"></textarea></td> </tr> <tr> <td style="width: 79px"> </td> <td style="width: 351px"> <input id="Submit1" style="width: 108px" type="submit" value="Get Method" language="javascript" onclick="return Submit1_onclick()" onserverclick="Submit1_ServerClick" runat="server" /> <asp:Button ID="Button1" runat="server" Text="Value Property" Width="111px" OnClick="Button1_Click" /></td> </tr> </table> </div> </div> </form> </body> </html>

Phn giao din thit k trang RequestFormGetPage.aspx

Phn m lnh thc thi trang RequestFormGetPage.aspx.cs


public partial class RequestFormGetPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Submit1_ServerClick(object sender, EventArgs e)

Lu hnh ni b

Trang 135

{ Response.Write("Email: " + Request.Form.Get("Email")); Response.Write("<br>Password: " + Request.Form.Get("Password")); Response.Write("<br>Address: " + Request.Form.Get("Address")); } protected void Button1_Click(object sender, EventArgs e) { Response.Write("Email: " +Email.Value ); Response.Write("<br>Password: " +Password.Value ); Response.Write("<br>Addres: " + Address.Value ); } }

Kt qu thc thi: Nhp d liu v click nt [Get Method]

Nhp d liu v click nt [Value Property]. Cho bit kt qu hin th.

Lu hnh ni b

Trang 136

Chng 4 :

QUN L TRNG THI

Cc vn chnh s c cp : Qun l trng thi ViewSate Chuyn thng tin gia cc trang. Cc i tng ca ASP.NET gm Cookies, Session v Application. Kt thc bi ny cc bn c th : Vn dng cc k thut trn qun l trng thi thng tin gia cc trang ASP.NET. M t c cc thuc tnh v phng thc ca cc i tng Session, Request Response, Server, Cookie v Application Trnh by v s dng c cc s kin trong tp tin Global.asax M t v s dng c cc thnh phn c bn trong tp tin Web.config S khc bit ng k nht gia lp trnh web form v lp trnh winform l qun l trng thi (state management) , lm th no bn lu tr thng tin qua cc vng i ca ng dng ca bn. Thng tin ny c th n gin nh tn ca ngi dng, hoc phc tp nh mt gi hng trong mt website thng mi in t. Trong mt ng dng Windows truyn thng, t cn phi suy ngh v qun l trng thi v do lun sn c b nh di do v bn ch cn phi quan tm v mt ngi dng duy nht. Trong mt ng dng web, l mt vn khc. Hng ngn ngi s dng c th ng thi chy cng mt ng dng trn cng mt my tnh (my ch web), mi mt giao tip vi HTTP khng lu trng thi (stateless protocol). Cc iu kin ny lm cho n khng th thit k mt ng dng web nh mt ng dng Windows truyn thng. S hiu bit v cc hn ch trng thi l cha kha to ra cc ng dng web hiu qu. Trong bi ny, bn s thy lm th no bn c th qun l trng thi ca ASP.NET vi cc tnh nng lu tr thng tin bo mt v nht qun. Bn s c cc ty chn lu tr khc nhau, bao gm xem trng thi (view state), trng thi phin giao dch (session), v ty chnh cookies. Bn cng s xem xt lm th no chuyn thng tin t trang ny sang trang khc bng cch s dng cross-page (post) v chui truy vn (quey string). 4.1 Vn ca Trng thi Trong mt chng trnh Windows truyn thng, ngi dng tng tc vi mt ng dng lin tc chy. Mt phn ca b nh trn my tnh bn c phn b lu tr cc thit lp hin hnh ca thng tin lm vic. Trong mt ng dng web, mt trang web ASP.NET chuyn nghip c th trng ging nh mt ng dng lin tc chy, nhng l thc s ch l mt o nh thng minh. Trong mt yu cu web in hnh, khch hng kt ni n my ch web v yu cu mt trang. Khi trang c chuyn giao, kt ni c ct t, v cc my ch web t b bt c thng tin n c v khch hng. Vi thi gian ngi s dng nhn c mt trang, do m trang web ny ngng chy nn khng c thng tin cn li trong b nh ca web server. Thit k ny c mt li th ng k. Bi v khch hng cn phi c kt ni ch trong mt vi giy l nhiu nht, do mt my ch web c th x l mt s lng ln cc yu cu gn nh ng thi. Tuy nhin, nu bn mun gi li thng tin hi gian n c th c s dng trn nhiu postbacks hoc trn nhiu trang, bn cn phi thc hin cc bc b sung. Lu hnh ni b Trang 137

4.2 Xem trng thi (View State) Cc iu khin Web Server Controls lu tr hu ht cc gi tr ca chng vo view state, khi thuc tnh EnableViewState c thit lp vi gi tr true (mc nh). Thuc tnh ViewState ca trang cung cp thng tin view state hin hnh. Thuc tnh ny l mt th hin ca lp StateBag. StateBag l mt t in, c mi mc c lu trong mt khe "ring" bng cch s dng mt tn chui duy nht. Th d, hy xem xt m ny:
this.ViewState["Counter"] = 1;

Lnh ny t gi tr 1 (hay ng hn, mt s nguyn c cha gi tr 1) vo trong ViewState. Nu hin ti khng c mc c tn Counter, mt mc mi s c thm t ng. Nu mt mc c lu tr di ci tn Counter, n s c thay th. Th d 1: To mt trang SimpleCounter.aspx c mt Button v Label.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SimpleCounter.aspx.cs" Inherits="SimpleCounter" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="cmdIncrement" runat="server" OnClick="cmdIncrement_Click" Text="Increment" /><br /> <br /> <asp:Label ID="lblCount" runat="server"></asp:Label>&nbsp;</div> </form> </body> </html>

Phn m lnh trang SimpleCounter.aspx.cs :


public partial class SimpleCounter : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void cmdIncrement_Click(object sender, EventArgs e) { int counter; if (ViewState["Counter"] == null) { counter = 1; } else { counter = (int)ViewState["Counter"] + 1; } ViewState["Counter"] = counter; lblCount.Text = "Counter: " + counter.ToString();

Lu hnh ni b

Trang 138

} }

Khi thc thi chng trnh, u tin ch xut hin button nh hnh sau:

Khi click vo button increment, gi tr counter c khi to bng 1 v gn cho ViewState vi tn Counter , v hin gi tr trn trang qua iu khin nhn lblCount: ViewState["Counter"] = counter; lblCount.Text = "Counter: " + counter.ToString(); Kt qu hin th:

Khi click tip hai ln trn button, gi tr ca bin counter c tng ln l 3, nh vy gi tr counter c duy tr qua cc ln request nh vo ViewSate[Counter]

Khi xem m ngun ca trang SimpleCounter qua trnh duyt, ni dung trang c cha khai bo _VIEWSTATE vi gi tr lu dng m Base64 (kiu m ho c bit ca chui v lun Lu hnh ni b Trang 139

lun c chp nhn trong mt ti liu HTML bi v n khng bao gm bt k k t m rng no) nh sau:
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTMyNDcxODYzNQ8WAh4HQ291bnRlcgIDFgICAw9kFgICAw8PFgIeBFRleHQFC kNvdW50ZXI6IDNkZGQYEc7So4CVsUXZm8qMxX0K6H/BQA==" />

Hnh 4.1 M ngun trang SimpleCounter.aspx c bin _VIEWSTAE. 4.3 Chuyn thng tin gia cc trang Phn ny trnh by hai cch thc chuyn thng tin gia cc trang bng cch s dng Crosspage Post v chui truy vn (quey string) 4.3.1 S dng Cross-Page Post Th d 2: To trang CrossPage1.aspx, vi hai nt lnh Cross-Page Postback v Manual Transfer cho php chuyn thng tin n trang CrossPage2.aspx bng k thut crosspage post vi khai bo thuc tnh PostBackUrl="CrossPage2.aspx" trong khai bo button [Cross-Page Postback] v cch chuyn thng thng vi Server.Transfer("CrossPage2.aspx", true); khi click button [Manual Transfer] Ni dung trang CrossPage1.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CrossPage1.aspx.cs" Inherits="CrossPage1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>CrossPage1</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head>

Lu hnh ni b

Trang 140

<body> <form id="form1" runat="server" > <div> First Name: <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox> <br /> Last Name: <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox> <br /> <asp:Button runat="server" ID="cmdPost" PostBackUrl="CrossPage2.aspx" Text="Cross-Page Postback" /><br /> <asp:Button runat="server" ID="cmdTransfer" Text="Manual Transfer" OnClick="cmdTransfer_Click" Visible="False" /> </div> </form> </body> </html>

<br />

M lnh trang
public partial class CrossPage1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["err"] != null) Page.Validate(); } protected void cmdTransfer_Click(object sender, EventArgs e) { Server.Transfer("CrossPage2.aspx", true); } public string FullName { get { return txtFirstName.Text + " " + txtLastName.Text; } } }

Thc thi trang CrossPage1.aspx, ni dung hin th nh sau: Nhp thng tin cho FirstName v LastName, sau click mt trong hai nt lnh u chuyn n trang CrossPage2.aspx

Sau khi click nt [Cross-Page Postback]

Lu hnh ni b

Trang 141

Trang CrossPage2.aspx: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CrossPage2.aspx.cs" Inherits="CrossPage2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server" > <div> <asp:Label ID="lblInfo" runat="server"></asp:Label></div> </form> </body> </html> Ni dung m lnh trang CrossPage2.aspx.cs :
public partial class CrossPage2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (PreviousPage != null) { lblInfo.Text = "You came from a page titled " + PreviousPage.Title + "<br />"; CrossPage1 prevPage = PreviousPage as CrossPage1; if (prevPage != null) { lblInfo.Text += "You typed in this: " + prevPage.FullName + "<br />"; } } } }

Lu hnh ni b

Trang 142

Trong m lnh trn ni dung FullName ch hin thi khi trang CrossPage2.aspx c chuyn n t trang CrossPage1.aspx vi mt trong hai cch trn. 4.3.2 S dng chui truy vn (Query String) Th d 3: To trang QueryStringSender.aspx, khi thc thi s chuyn gi tr cc iu khin trn trang n trang QuerStringRecipient.aspx qua chui truy vn gn vo chui url. Ni dung trang QueryStringSender.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="QueryStringSender.aspx.cs" Inherits="QueryStringSender" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ListBox ID="lstItems" runat="server" Height="155px" Width="165px"> </asp:ListBox><br /> <br /> <asp:CheckBox ID="chkDetails" runat="server" Text="Show full details" /><br /> <br /> <asp:Button ID="cmdGo" runat="server" OnClick="cmdGo_Click" Text="View Information" Width="165px" /><br /> <br /> <asp:Label ID="lblError" runat="server" EnableViewState="False"></asp:Label> </div> </form> </body> </html>

Phn m lnh QueryStringSender.aspx.cs:


public partial class QueryStringSender : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack){ // Add sample values. lstItems.Items.Add("Econo Sofa"); lstItems.Items.Add("Supreme Leather Drapery"); lstItems.Items.Add("Threadbare Carpet"); lstItems.Items.Add("Antique Lamp"); lstItems.Items.Add("Retro-Finish Jacuzzi"); } } protected void cmdGo_Click(object sender, EventArgs e) { if (lstItems.SelectedIndex == -1) { lblError.Text = "You must select an item."; } else { // Forward the user to the information page, with the query string data.

Lu hnh ni b

Trang 143

string url = "QueryStringRecipient.aspx?"; url += "Item=" + Server.UrlEncode(lstItems.SelectedItem.Text) + "&"; url += "Mode=" + chkDetails.Checked.ToString(); Response.Redirect(url); } }}

Khi click nt [View Information] s chuyn n trang QueryStringRecipient.aspx cng vi chui truy vn nh sau : http://localhost:1222/StateManagement/QueryStringRecipient.aspx?Item=Threadbare + Carpet&Mode=True

Kt qu hin th ca trang QueryStringRecipient.aspx :

Ni dung trang QueryStringRecipient.aspx :


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="QueryStringRecipient.aspx.cs" Inherits="QueryStringRecipient" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body>

Lu hnh ni b

Trang 144

<form id="form1" runat="server"> <div style="border-right: 2px solid; padding-right: 30px; border-top: 2px solid; padding-left: 30px; font-weight: bold; font-size: 140%; padding-bottom: 30px; border-left: 2px solid; padding-top: 30px; border-bottom: 2px solid; font-family: Verdana; background-color: #FFFFD9"> <asp:Label ID="lblInfo" runat="server" EnableViewState="False" ></asp:Label> </div> </form> </body> </html>

Phn m lnh ca trang QueryStringRecipient.aspx.cs: public partial class QueryStringRecipient : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblInfo.Text = "Item: " + Request.QueryString["Item"]; lblInfo.Text += "<br />Show Full Record: "; lblInfo.Text += Request.QueryString["Mode"]; } } 4.4 i tng Cookies C l bn cng tng ng k l mt thnh vin ca mt trang web hay mt forum no , v chc cng khng t ln ngc nhin khi bn va yu cu n mt trang web hay forum m bn ng k trc , trang web nhn ngay ra, bn chnh l thnh vin ca h v gi ngay li cho n bn, chng hn: Cho Nguyn Vn An. Nhng thng tin ca bn khi ng nhp hay khi ng k c lu ngay chnh ti my ca bn. Nhng thng tin ny c Web Server lu ti my Client c gi l Cookies. Khng ging nh i tng Session, i tng Cookies cng c dng lu tr thng tin ca ngi dng, tuy nhin, thng tin ny c lu ngay ti my gi yu cu n Web Server. C th xem mt Cookie nh mt tp tin (vi kch thc kh nh) c Web Server lu ti my ca ngi dng. Mi ln c yu cu n Web Server, nhng thng tin ca Cookies cng s c gi theo v Server.

Hnh 4.2 Minh ho Cookies. Lm vic vi Cookies Thm Cookies Lu hnh ni b Trang 145

Response.Cookies.Add(<HttpCookie>) Th d: HttpCookie ck = new HttpCookie("TenDangNhap"); ck.Value = txtTenDangNhap.Text; ck.Expires = DateTime.Now.AddDays(15); Response.Cookies.Add(ck); Trong th d trn, chng ta to ra Cookies c tn l TenDangNhap lu tr tn ng nhp ca ngi dng. Thng tin ny s c lu tr trn Cookies 15 ngy k t ngy hin hnh trn Web Server. Ly gi tr t Cookies HttpCookie ck = Request.Cookies["TenDangNhap"]; string s = ck.Value; Trong trng hp Cookies cha c lu hoc ht thi hn duy tr ti Client, gi tr nhn c l null. Th d: To trang <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CookieExample.aspx.cs" Inherits="CookieExample" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <div style="border-right: 2px solid; padding-right: 30px; border-top: 2px solid; padding-left: 30px; font-weight: bold; font-size: 140%; padding-bottom: 30px; borderleft: 2px solid; padding-top: 30px; border-bottom: 2px solid; font-family: Verdana; background-color: #FFFFD9"> <asp:Label ID="lblWelcome" runat="server" EnableViewState="False" ></asp:Label> </div> <br /> Name: <asp:TextBox ID="txtName" runat="server" Width="178px"></asp:TextBox> <asp:Button ID="cmdStore" runat="server" OnClick="cmdStore_Click" Text="Create Cookie" /> </div> </form> </body> </html> Khi click nt [Create Cookie], phn m lnh thc thi nh sau: public partial class CookieExample : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) Lu hnh ni b Trang 146

{ HttpCookie cookie = Request.Cookies["Preferences"]; if (cookie == null) { lblWelcome.Text = "<b>Unknown Customer</b>"; } else { lblWelcome.Text = "<b>Cookie Found.</b><br><br>"; lblWelcome.Text += "Welcome, " + cookie["Name"]; } } protected void cmdStore_Click(object sender, EventArgs e) { // Check for a cookie, and only create a new one if // one doesn't already exist. HttpCookie cookie = Request.Cookies["Preferences"]; if (cookie == null) { cookie = new HttpCookie("Preferences"); } cookie["Name"] = txtName.Text; cookie.Expires = DateTime.Now.AddYears(1); Response.Cookies.Add(cookie); lblWelcome.Text = "<b>Cookie Created.</b><br><br>"; lblWelcome.Text += "New Customer: " + cookie["Name"]; } } Khi thc thi trang CookieExample.aspx :

Click nt [Create Cookie], trnh ch (web server) s to mt Cookie tn Name c gi tr l Dao Nguyen ghi li trn my khch vi thi hn lu tr l mt nm. cookie["Name"] = txtName.Text; cookie.Expires = DateTime.Now.AddYears(1); Response.Cookies.Add(cookie); Kt qu hin th sau khi click nt [Create Cookie]: Lu hnh ni b Trang 147

Gi thc thi li trang CookieExample.aspx ln th hai tr i, kt qu hin th trang:

4.5 i tng Session i tng Session c dng lu tr thng tin ca ngi dng trong ng dng. Thng tin c lu tr trong Session l ca mt ngi dng trong mt phin lm vic c th. Web Server s t ng to mt i tng Session cho mi ngi dng mi kt ni vo ng dng v t ng hy chng nu ngi dng cn khng lm vic vi ng dng na. Tuy nhin, khng ging nh i tng Application, i tng Session khng th chia s thng tin gia nhng ln lm vic ca ngi dng, n ch c th cung cp, trao i thng tin cho cc trang trong ln lm vic tng ng. Trong ng dng web, i tng Session gi vai tr kh quan trng. Do s dng giao thc HTTP, mt giao thc phi trng thi, Web Server hon ton khng ghi nh nhng g gia nhng ln yu cu ca Client. i tng Session t ra kh hu hiu trong vic thc hin "lu vt v qun l thng tin ca ngi dng". Thuc tnh & Phng thc Thuc tnh Timeout Qui nh khong thi gian (tnh bng pht) m Web Server duy tr i tng Session nu ngi dng khng gi yu cu no v li Server. Gi tr mc nh ca thuc tnh ny l 20. Nu khng c yu cu no k t ln yu cu sau cng mt khong thi gian l <Timeout> pht, i tng Session m Web server cp cho ln lm vic s t ng c gii phng. Nhng yu cu sau c Web server coi nh l mt ngi dng mi, v ng nhin s c cp mt i tng Session mi. Phng thc Abandon Lu hnh ni b Trang 148

Nh cc bn bit, trong khong thi gian <Timeout> pht k t ln yu cu sau cng ca Client, i tng Session vn c duy tr d cho khng c s tng tc no ca Client. iu ny ng ngha vi vic Web server phi s dng mt vng nh duy tr i tng Session trong mt khong thi gian tng ng. Phng thc Abandon ca i tng Session s gii phng vng nh c dng duy tr i tng Session trn Web Server ngay khi c gi thc hin. Nhng yu cu sau c Web server coi nh l mt ngi dng mi. S dng bin ton cc vi Session To bin Session Session["Tn bin"] = <gi tr> Ly gi tr t bin Session <bin> = Session["Tn bin"] Th d: Minh ha s dng bin session lu thng tin ca ngi dng khi ng nhp To ng dng Web gm cc trang ASP.Net c m t nh sau : Trang DangNhap.aspx Control Lable Lable TextBox TextBox Tn thuc tnh Gi tr thuc tnh Text Tn ng nhp Text Mt khu ID txtTenDangNhap ID txtMatKhau Text ng nhp Button ID btnangNhap Bng m t cc thuc tnh ca cc controls trang DangNhap.aspx.

Thit k giao din trang DangNhap.aspx X l s kin


public partial class DangNhap : System.Web.UI.Pag { protected void Page_Load(object sender, EventArgs e) { } protected void btnDangNhap_Click(object sender, EventArgs e) { if (txtTenDangNhap.Text == "An" && txtMatKhau.Text == "123") { Session["TenDangNhap"] = txtTenDangNhap.Text; Response.Redirect("ChaoMung.aspx"); } }}

Trang ChaoMung.aspx :

Lu hnh ni b

Trang 149

public partial class ChaoMung : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Ly gi tr t bin Session string s = Session["TenDangNhap"].ToString(); Response.Write("Chc mng bn &nbsp;" + s + "&nbsp; ng nhp thnh cng."); }}

Kt qu thi hnh cc trang ASP.Net

Kt qu sau khi nhp thng tin v click nt [ng nhp]

4.6 i tng Application Application v Session l hai i tng kh quan trng trong ng dng web, gip cc trang aspx c th lin kt v trao i d liu cho nhau. Trong phn ny, chng ta s tm hiu v s dng hai i tng ny trong ng dng.

Lu hnh ni b

Trang 150

Hnh 4.3 Minh ho quan h ca i tng Session v Appliaction. i tng Application c s dng qun l tt c cc thng tin ca mt ng dng web. Thng tin c lu tr trong i tng Application c th c x l trong bt k trang aspx no trong sut chu k sng ca ng dng. S dng bin Application To bin Application Application["Tn bin"] = <gi tr> Ly gi tr t bin Application <bin> = Application["Tn bin"] Th d:
Application.Lock() Application["SoLanTruyCap"] = 0 Application["SoNguoiOnLine"] = 0 Application.UnLock()

Ch : Do ti mt thi im c th c nhiu ngi cng lc truy cp v thay i gi tr ca cc thng tin c lu trong i tng Application, chng ta nn s dng b lnh Lock v UnLock ngay trc v sau khi cp nht gi tr ca bin Application. Bin Application c th c s dng bt k trang no v c duy tr trong sut chu k sng ca ng dng. Lu hnh ni b Trang 151

Th d minh ha s dng bin Application . To mt ng dng Web gm 2 trang ASP.Net sau y :

Hnh 4.4: Thit k trang SuDungApplication.aspx X l s kin trang SuDungApplication.aspx


public partial class SuDungApplication : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e){ } protected void btnXemHoTen_Click(object sender, EventArgs e) { //Khai bo bin ng dng Application["HoTen"] = txtHoTen.Text; Response.Redirect("~/LayGiaTri.aspx"); } }

To trang LayGiaTri.aspx v vit lnh x l s kin nh sau :


public partial class LayGiaTri : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string s = Application["HoTen"].ToString(); Response.Write("Tn ca bn : "+s); } }

Kt qu thc hin:

Lu hnh ni b

Trang 152

Trang SuDungApplication.aspx

Trang LayGiaTri.aspx 4.7 Tp tin Global.asax Tp tin Global.asax c dng : Khai bo v khi to gi tr cho cc bin Application, Session. Vit x l cho cc s kin ca 2 i tng Application v Session. Cc s kin trong tp tin Global.asax Application_Start: Ch xy ra mt ln u tin khi bt k trang no trong ng dng c gi.
protected void Application_Start(object sender, EventArgs e) { //Khai bo bin Application m s ngi truy cp Application["SoNguoiTruyCap"] = 0; Application["SoNguoiOnline"] = 0; }

Session_Start: Xy ra khi c mt ngi dng mi yu cu n bt k trang aspx ca ng dng. Khi Session_Start xy ra, mt gi tr duy nht (SessionID) s c to cho ngi dng, v gi tr ny c s dng qun l ngi dng trong qu trnh lm vic vi ng dng.
protected void Session_Start(object sender, EventArgs e) { //Tng gi tr bin Application Application["SoNguoiTruyCap"]=(int)Application["SoNguoiTruyCap"]+1; Application["SoNguoiOnline"]=(int)Application["SoNguoiOnline"] +1 ; }

Application_BeginRequest: Xy ra khi mi khi c Postback v Server. Application_Error: Xy ra khi c li pht sinh trong qu trnh thi hnh. Session_End: Xy ra khi phin lm vic khng c gi yu cu hoc lm ti trang aspx ca ng dng web trong mt khong thi gian (mc nh l 20 pht). Lu hnh ni b Trang 153

protected void Session_End (object sender, EventArgs e) { //gim gi tr bin Application Application["SoNguoiOnline"]=(int)Application["SoNguoiOnline"]-1 ; }

Application_End: Xy ra khi dng hot ng ca WebServer. V d x l ghi nhn thng tin S lt truy cp vo c s d liu (nu cn). 4.8 Tp tin Web.config Cu trc tp tin web.config Web.config l mt tp tin vn bn c s dng lu tr thng tin cu hnh ca mt ng dng, c t ng to ra khi chng ta to mi ng dng web. Tp tin web.config c vit theo nh dng XML. Web.config c to k tha cc gi tr t tp tin Windows\Microsoft.NET\ Framework \ \[FrameworkVersion]\CONFIG\machine.config Cc cu hnh mc nh <compilation debug="false"/> : qui nh ngn ng mc nh ca ng dng C#. debug: Bt/tt ch debug ca ng dng <customErrors mode="RemoteOnly"/> y l mt cu hnh kh cn thit cho ng dng Web. Hiu chnh cu hnh ny cho php chng ta qun l vic x l li khi c li pht sinh trong ng dng. Thuc tnh mode c cc gi tr: RemoteOnly, On v Off. RemoteOnly: Cho php ngi dng thy thng bo li ca h thng hoc trang thng bo li c ch nh qua defaultRedirect (nu c). Thng bo li gm: M li v m t li tng ng
<customErrors mode="RemoteOnly" defaultRedirect="TrangThongBaoLoi.htm"/>

On: Ty theo gi tr ca defaultRedirect m c cc trng hp tng ng: C qui nh trang thng bo li qua defaultRedirect: Hin th trang thng bo li.

Khng c thuc tnh defaultRedirect: Hin th trang bo li nhng khng c hin th m li v m t li.

Lu hnh ni b

Trang 154

Off: Hin th thng bo li ca trang aspx (nu xy ra li).

Lu hnh ni b

Trang 155

<sessionState/>
<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20" />

mode: Thuc tnh ny c 3 gi tr: InProc, sqlserver (lu trong database), v stateserver (lu trong b nh) stateConnectionString: Cu hnh a ch v cng (port) ca my lu tr thng tin ca Session trong vng nh (nu chc nng ny c chn). sqlConnectionString: Cu hnh kt ni n SQL Server c dng lu thng tin Session (nu chc nng ny c chn). cookieless: Nu gi tr ca thuc tnh ny = True, thng tin cookie s c lu tr trong URL, ngc li, nu = False, thng tin cookies s c lu tr ti client (nu client c h tr) timeout: Khong thi gian (tnh bng pht) m i tng Session c duy tr. Sau khong thi gian ny, i tng Session s b hu. Gi tr mc nh ca thuc tnh ny l 20.

Lu hnh ni b

Trang 156

BI THC HNH CHNG 4: Bi 1: Thc hnh li cc bi tp th d trong bi hc, c th hiu chnh li theo hc vin. Bi 2: c v gii thch ni dung ca Phn m lnh trang SessionEx1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SessionEx1.aspx.cs" Inherits="SessionEx1" %> <!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 id="Head1" runat="server"> <title>Sessions</title> </head> <body runat="server" id="BodyTag"> <div> <form id="form1" runat="server"> <asp:DropDownList runat="server" id="ColorSelector" autopostback="true" onselectedindexchanged="ColorSelector_IndexChanged"> <asp:ListItem value="White" selected="True">Select color...</asp:ListItem> <asp:ListItem value="Red">Red</asp:ListItem> <asp:ListItem value="Green">Green</asp:ListItem> <asp:ListItem value="Blue">Blue</asp:ListItem> </asp:DropDownList> </form> </div> </body> </html> Trang thit k ca SessionEx1.aspx

Phn m lnh trang SessionEx1.aspx.cs


public partial class SessionEx1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["BackgroundColor"] != null) { ColorSelector.SelectedValue = Session["BackgroundColor"].ToString(); BodyTag.Style["background-color"] = ColorSelector.SelectedValue; } } protected void ColorSelector_IndexChanged(object sender, EventArgs e) { BodyTag.Style["background-color"] = ColorSelector.SelectedValue; Session["BackgroundColor"] = ColorSelector.SelectedValue; }

Lu hnh ni b

Trang 157

Khi chn mu Green t DropdownList, kt qu thc thi trang:

Kt thc ng dng v chy li ng dng n trong cng mt ca s trnh duyt ang m, trang hin th ra sao? Gii thch. Nu ng ca s trnh duyt v thc thi li ng dng , trang hin th ra sao? Gii thch. Bi 3: To mt ng dng ASP.NET v i tng Application v tp tin Global.asax -To trang Global.asax
<%@ Application Language="C#" %> <script runat="server"> void Application_Start(object sender, EventArgs e) { int SiteHitCounter=500; int CurrentUsers=100; Application["SiteHitCounter"] = SiteHitCounter; Application["CurrentUsers"] = CurrentUsers; } void Application_End(object sender, EventArgs e) { HitCountClass cls = new HitCountClass(); } void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs } void Session_Start(object sender, EventArgs e) { Application["SiteHitCounter"] = (int)Application["SiteHitCounter"] + 1; Application["CurrentUsers"] = (int)Application["CurrentUsers"] + 1; } void Session_End(object sender, EventArgs e) { Application["CurrentUsers"] = (int)Application["CurrentUsers"] - 1; // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. } </script>

Lu hnh ni b

Trang 158

- To trang ApplicationPage.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ApplicationPage.aspx.cs" Inherits="ApplicationPage" %> <!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 runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Literal ID="Literal1" runat="server"></asp:Literal><br /> <br /> <asp:Literal ID="Literal2" runat="server"></asp:Literal>&nbsp;</div> </form> </body> </html> - To trang ApplicationPage.aspx.cs public partial class ApplicationPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Literal1.Text = "Hit Counter: " + Application["SiteHitCounter"] .ToString(); Literal2.Text = "Current users: " + Application["CurrentUsers"].ToString(); } }

Kt qu thc thi trang ApplicationPage.aspx

Lu hnh ni b

Trang 159

Chng 5:

S DNG CC VALIDATION CONTROLS

Cc vn chnh s c cp : M t c cc thuc tnh v s dng cc Validation Controls Kt thc bi ny cc bn c th : Vn dng cc Validation Controls kim chng thng tin cc trang ASP.NET. Khi xy dng ng dng, chng ta nn kim tra d liu nhp t ngi dng hn ch cc sai st d liu nhp nhm m bo vic thc hin x l d liu c chnh xc theo cc yu cu nghip v. Nu chng ta vit m kim tra phi mt nhiu thi gian (s dng JavaScript hoc VBScript). Webform h tr cc validation controls kim tra d liu nhp t ngui dng trong cc sever controls , mc ch l trnh ngi dng nhp sai hoc khng c b trng cc thng tin quan trng bt buc, Vi phin bn trc ca ASP.Net l ASP th khc phc li chng ta phi thc hin vit m JavaScript bt li vic , cn vi ASP.NET cung cp cho ta nhng iu khin kim tra tnh hp l ca cc iu khin nhp liu trn Form. Trong bi ny cc bn s hc v nhng iu khin v tip theo l s hc cch m rng nhng iu khin theo mun ca chng ta th d bn s to mt AjaxValidator kim tra nhp liu pha Client. C 6 iu khin Validation trong .Net framework 3.5: RequiredFieldValidator: Yu cu ngi s dng nhp gi tr vo trng ch nh trn Form RangeValidator: Kim tra gi tr nhp vo c nm trong mt khong nh nht v ln nht nh trc hay khng. CompareValidator: So snh gi tr nhp c bng mt gi tr ca trng khc trn Form hay khng. RegularExpressionValidator: So snh gi tr nhp vi 1 biu thc quy tc no y c th l email, s in thoi, s ti khon ngn hng CustomValidator: Bn c th tu chnh i tng Validator theo ca mnh ValidationSummary: cho php hin th tng hp tt c cc li trn 1 trang.

Hnh 5.1 S kim tra d liu nhp trn Form ti Client v Server Lu hnh ni b Trang 160

Nh cc bn bit, mi khi PostBack v Server, trang Web lun kim tra tnh hp l d liu (nu c yu cu khi thit k). Nu d liu khng hp l (b trng, vi phm min gi tr, mt khu nhp li khng ng, ), trang web s khng th PostBack v Server. Cc thuc tnh chung ca cc validation control Thuc tnh ngha Tn iu khin cn kim tra. y l thuc tnh m cc bn phi xc ControlToValidate nh khi s dng Validation Control. Chui thng bo xut hin khi c li. Text ErrorMessage Chui thng bo xut hin trong iu khin Validation Summary. Gi tr ny s c hin th ti v tr ca iu khin nu chng ta khng gn gi tr cho thuc tnh Text. Qui nh hnh thc hin th: None: Khng hin th thng bo li (vn c kim tra d liu) Static: Trong trng hp khng c vi phm d liu, iu khin khng c hin th nhng vn chim v tr nh trong lc thit k. Dynamic: Trong trng hp khng c vi phm d liu, iu khin khng chim dng v tr trn mn hnh. C cho php thc hin kim tra pha Client hay khng ?. Gi tr mc nh l true - c kim tra.

Display

EnableClientScript

5.1 RequiredFieldValidator 1. ngha: vi iu khin ny bn c th yu cu ngi dng phi nhp gi tr vo 1 trng ch nh trn Form. 2. Cch s dng: a iu khin RequiredFieldValidator t ToolBox (trong phn Validation) vo trong Form v thm vo cho n 2 thuc tnh : ControlToValidate: ch n iu khin nhp liu s c kim tra. Text(hoc ErrorMessage): Thng bo li khi kim tra c li xy ra. Th d 1: To trang RequiredFieldValidate1.aspx c s dng iu khin kim chng RequiredFieldValidator cho iu khin nhp TextBox :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RequiredFieldValidate1.aspx.cs" Inherits="RequiredFieldValidate1" %>

Lu hnh ni b

Trang 161

<!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 runat="server"> <title>Untitled Page</title> <script runat="server"> void ValidateBtn_Click(Object sender, EventArgs e) { if (Page.IsValid) { lblOutput.Text = "Required field is filled!"; } else { lblOutput.Text = "Required field is empty!"; } } </script> </head> <body> <form id="form1" runat="server"> <div> <h3>RequiredField Validator Example</h3> <table style="background-color:#eeeeee; padding:10"> <tr valign="top"> <td colspan="3"> <asp:Label ID="lblOutput" Text="Fill in the required field below" runat="server" AssociatedControlID="TextBox1"/> <br /> </td> </tr> <tr> <td colspan="3"> <b>Credit Card Information</b> </td> </tr> <tr> <td align="right"> Card Number: </td> <td> <asp:TextBox id="TextBox1" runat="server"/> </td> <td> <asp:RequiredFieldValidator id="RequiredFieldValidator2" ControlToValidate="TextBox1" Display="Static" ErrorMessage="*" runat="server"/>

Lu hnh ni b

Trang 162

</td> </tr> <tr> <td></td> <td> <asp:Button id="Button1" Text="Validate" OnClick="ValidateBtn_Click" runat="server"/> </td> <td></td> </tr> </table> </div> </form> </body> </html>

Giao din trang

Khi bn khng nhp d liu cho khung nhp Card Number, v click nt Validate, s xut hin thng bo li bn cnh khung nhp (*):

Thng bo li s khng xut hin khi bn nhp d liu trong khung nhp.

Lu hnh ni b

Trang 163

5.2 iu khin RangeValidator 1. ngha Bn c th s dng RangeValidator Kim tra gi tr nhp vo c nm trong mt khong nh nht v ln nht nh trc hay khng. 2. Cch s dng Bn a iu khin RangeValidator t hp ToolBox vo Form v thit lp cho n mt s thuc tnh sau: ControlToValidate: ch n iu khin cn kim tra Text(ErrorMessage): Ni dung thng bo li MinimumValue: Gi tr nh nht thit lp cho i tng MaximumValue: Gi tr ln nht thit lp cho i tng Type: Kiu so snh, C th l cc gi tr Interger,String, Double, Date v Currency. Th d 2: To trang RangeValidator.aspx s dng iu khin kim tra d liu RangeValidator kim tra phm vi nhp mt s nguyn c gi tr t 1 n 10 trong khung nhp.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RangeValidator.aspx.cs" Inherits="RangeValidator" %> <!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 runat="server"> <title>RangeValidator Example</title> <script runat="server"> void ButtonClick(Object sender, EventArgs e) { if (Page.IsValid) { Label1.Text="Page is valid."; } else { Label1.Text="Page is not valid!!"; } } </script>

Lu hnh ni b

Trang 164

</head> <body> <form id="form1" runat="server"> <div> <h3>RangeValidator Example</h3> Enter a number from 1 to 10: <br /> <asp:TextBox id="TextBox1" runat="server"/> <br /> <asp:RangeValidator id="Range1" ControlToValidate="TextBox1" MinimumValue="1" MaximumValue="10" Type="Integer" EnableClientScript="false" Text="The value must be from 1 to 10!" runat="server"/> <br /><br /> <asp:Label id="Label1" runat="server"/> <br /><br /> <asp:Button id="Button1" Text="Submit" OnClick="ButtonClick" </div> </form> </body> </html>

runat="server"/>

Giao din thit k trang RangeValidator.aspx

Kt qu thc thi khi click nt lnh Submit, phng thc x l p ng s kin OnClick trn nt lnh nh sau:
void ButtonClick(Object sender, EventArgs e) { if (Page.IsValid) { Label1.Text="Page is valid."; } else { Label1.Text="Page is not valid!!"; } }

Lu hnh ni b

Trang 165

Kt qu hin th:

5.3 iu khin CompareValidator 1. ngha Bn c th s dng CompareValidator kim tra gi tr nhp vo c nm trong mt khong nh nht v ln nht nh trc hay khng. 2. Cch s dng Thng qua thuc tnh Operator, chng ta c th thc hin cc php so snh nh: =, <>, >, >=, <, <= hoc dng kim tra kiu d liu (DataTypeCheck). S dng iu khin ny kim tra rng buc min gi tr, kiu d liu, lin thuc tnh. Lu : Trong trng hp khng nhp d liu, iu khin s khng thc hin kim tra vi phm. Cc thuc tnh ControlToCompare: Tn iu khin cn so snh gi tr. Nu bn chn gi tr ca thuc tnh Operator = DataTypeCheck th khng cn phi xc nh gi tr cho thuc tnh ny. Operator: Qui nh php so snh, kim tra kiu d liu o Equal: = (y l gi tr mc nh) o GreaterThan: > o GreaterThanEqual: >= o LessThan: < o LessThanEqual: <= o NotEqual: <> o DataTypeCheck: Kim tra kiu d liu Type: Qui nh kiu d liu kim tra hoc so snh. o String o Integer o Double o Date o Currency ValueToCompare: Gi tr cn so snh. Trong trng hp bn xc nh gi tr ca c 2 thuc tnh ControlToCompare v ValueToCompare th gi tr ca iu khin c qui nh bi thuc tnh ControlToCompare c u tin dng kim tra. Lu hnh ni b Trang 166

Th d 3: To trang CompareValidatorEx.aspx vi ni dung thit k s dng iu khin CompareValidator kim chng vic so snh bng (mc nh) gi tr chui nhp trong hai khung nhp String 1(TextBox1) v String 2 (TextBox2) :
<asp:CompareValidator id="Compare1" ControlToValidate="TextBox1" ControlToCompare="TextBox2" EnableClientScript="False" Type="String" runat="server"/> Ni dung trang CompareValidatorEx.aspx: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CompareValidatorEx.aspx.cs" Inherits="CompareValidatorEx" %> <!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 runat="server"> <title>CompareValidator Example</title> <script runat="server"> void Button_Click(Object sender, EventArgs e) { if (Page.IsValid) { lblOutput.Text = "Result: Valid!"; } else { lblOutput.Text = "Result: Not valid!"; } } void Operator_Index_Changed(Object sender, EventArgs e) { Compare1.Operator = (ValidationCompareOperator) ListOperator.SelectedIndex; Compare1.Validate(); } void Type_Index_Changed(Object sender, EventArgs e) { Compare1.Type = (ValidationDataType) ListType.SelectedIndex; Compare1.Validate(); } </script> </head> <body> <form id="form1" runat="server"> <div> <h3>CompareValidator Example</h3><br /> Enter a value in each textbox. Select a comparison operator<br /> and data type. Click "Validate" to compare values. <table style="background-color:#eeeeee; padding:10"> <tr valign="top"> <td> <h5>String 1:</h5> <asp:TextBox id="TextBox1" runat="server"/> </td> <td> <h5>Comparison Operator:</h5> <asp:ListBox id="ListOperator"

Lu hnh ni b

Trang 167

OnSelectedIndexChanged="Operator_Index_Changed" runat="server"> <asp:ListItem Selected="True" Value="Equal">Equal</asp:ListItem> <asp:ListItem Value="NotEqual">NotEqual</asp:ListItem> <asp:ListItem Value="GreaterThan">GreaterThan</asp:ListItem> <asp:ListItem Value="GreaterThanEqual">GreaterThanEqual</asp:ListItem> <asp:ListItem Value="LessThan">LessThan</asp:ListItem> <asp:ListItem Value="LessThanEqual">LessThanEqual</asp:ListItem> <asp:ListItem Value="DataTypeCheck">DataTypeCheck</asp:ListItem> </asp:ListBox> </td> <td> <h5>String 2:</h5> <asp:TextBox id="TextBox2" runat="server"/> <br /> <asp:Button id="Button1" Text="Validate" OnClick="Button_Click" runat="server"/> </td></tr> <tr> <td colspan="3" align="center"> <h5>Data Type:</h5> <asp:ListBox id="ListType" OnSelectedIndexChanged="Type_Index_Changed" runat="server"> <asp:ListItem Selected="true" Value="String" >String</asp:ListItem> <asp:ListItem Value="Integer" >Integer</asp:ListItem> <asp:ListItem Value="Double" >Double</asp:ListItem> <asp:ListItem Value="Date" >Date</asp:ListItem> <asp:ListItem Value="Currency" >Currency</asp:ListItem> </asp:ListBox> </td> </tr> </table> <asp:CompareValidator id="Compare1" ControlToValidate="TextBox1" ControlToCompare="TextBox2" EnableClientScript="False" Type="String" runat="server"/> <br /> <asp:Label id="lblOutput" Font-Names="verdana" Font-Size="10pt" runat="server"/> </div> </form> </body> </html>

Phn m thc thi p ng s kin xy ra khi thay i ni dung trong hai ListBox (s kin OnSelectedIndexChanged) v Button (s kin OnClick), cho php cp nht li gi tr Operator cho iu khin CompareValidator.
<script runat="server"> void Button_Click(Object sender, EventArgs e) { if (Page.IsValid) { lblOutput.Text = "Result: Valid!"; } else { lblOutput.Text = "Result: Not valid!";

Lu hnh ni b

Trang 168

} } void Operator_Index_Changed(Object sender, EventArgs e) { Compare1.Operator = (ValidationCompareOperator) ListOperator.SelectedIndex; Compare1.Validate(); } void Type_Index_Changed(Object sender, EventArgs e) { Compare1.Type = (ValidationDataType) ListType.SelectedIndex; Compare1.Validate(); } </script> Giao din trang CompareValidatorEx.aspx vi hai ln thc thi so snh hai chui vi php ton

so snh bng (Equal) hay khc (Not Equal):

5.4 iu khin RegularExpressionValidator 1. ngha iu khin RegularExpressionValidator cho php bn so snh gi tr nhp ti 1 trng no trn Form vi mt quy tc nh trc. bn c th s dng cc biu thc quy tc a ra cc chui mu nh l email addresses, Social Security numbers, phone numbers, dates, currency, amounts, hoc product codes 2. Cch s dng Bn a iu khin RegularExpressionValidator vo Form ca mnh v thit lp cho n mt s thuc tnh sau: ID: tn ca iu khin ControlToValidate: tr n iu khin cn kim tra Text(ErrorMessage): ni dung thng bo khi c li ValidatorExpression: quy nh mu nhp liu nh l email, s in thoi Bng m t cc k hiu thng s dng trong Validation Expression K hiu M t K t ch ci ( c xc nh). y l ch a A K t s ( c xc nh). y l s 1 1 Lu hnh ni b Trang 169

[0-n] [abc] | \w \d

Mt k t s t 0 n 9 Mt k t: hoc a hoc b hoc c La chn mu ny hoc mu khc K t thay th phi l mt k t ch ci K t thay th phi l mt k t s

Th hin cc k t c bit theo sau. \ K t thay th phi l du chm cu (.) \. Qui nh s ln xut hin: 0 hoc 1 ln ? Qui nh s ln xut hin: 0 hoc nhiu ln * Qui nh s ln xut hin: 1 hoc nhiu ln (t nht l 1) + Qui nh s ln xut hin: ng n ln {n} Th d 3: To trang RegularExpressionValidatorEx.aspx s dng iu khin kim tra RegularExpressionValidator quy nh d liu nhp cho khung nhp ZipCode l s v phi l 5 ch s.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RegularExpressionValidatorEx.aspx.cs" Inherits="RegularExpressionValidatorEx" %> <!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 runat="server"> <title>RegularExpressionValidator Example</title> <script runat="server"> void ValidateBtn_Click(Object sender, EventArgs e) { if (Page.IsValid) { lblOutput.Text = "Page is Valid."; } else { lblOutput.Text = "Page is InValid."; } } </script> </head> <body> <form id="form1" runat="server"> <div> <h3>RegularExpressionValidator Example</h3> <table style="background-color:#eeeeee; padding:10"> <tr valign="top"> <td colspan="3"> <asp:Label ID="lblOutput" Text="Enter a 5-digit ZIP Code"

Lu hnh ni b

Trang 170

runat="server" AssociatedControlID="TextBox1"/> </td> </tr> <tr> <td colspan="3"> <b>Personal Information</b> </td> </tr> <tr> <td align="right"> Zip Code: </td> <td> <asp:TextBox id="TextBox1" runat="server"/> </td> <td> <asp:RegularExpressionValidator id="RegularExpressionValidator1" ControlToValidate="TextBox1" ValidationExpression="\d{5}" Display="Static" ErrorMessage="ZIP code must be 5 numeric digits" EnableClientScript="False" runat="server"/> </td> </tr> <tr> <td></td> <td> <asp:Button ID="Button1" text="Validate" OnClick="ValidateBtn_Click" runat="server" /> </td> <td></td> </tr> </table> </div> </form> </body> </html> Giao din trang RegularExpressionValidatorEx.aspx :

Lu hnh ni b

Trang 171

Khi click nt Validate, phng thc p ng s kin click ValidateBtn_Click c ni dung nh sau:
void ValidateBtn_Click(Object sender, EventArgs e) { if (Page.IsValid) { lblOutput.Text = "Page is Valid."; } else { lblOutput.Text = "Page is InValid."; } }

Dng thuc tnh Page.IsValid kim tra d liu nhp trn Form nhp c hp l hay khng. Kt qu thc thi cho hai trng hp d liu nhp khng hp l v hp l:

5.5 iu khin CustomValidator 1. ngha Nu nhng iu khin Validator trn cha vi bn hoc bn mun to mt Validator ring theo mnh, bn c th dng iu khin CustomValidator, bn c th kt hp CustomValidator vi mt hm. 2. Cch s dng CustomValidator c 3 thuc tnh hay s dng l: ControlToValidator: iu khin ca Form s c kim tra Text(ErrorMessage): hin th ni dung thng bo li kho c li ClientValidationFunction: tn ca mt hm client-side thc hin kim tra trn client-side

CustomValidator h tr 1 s kin: ServerValidate: S kin c a ra khi CustomValidator thc hin kim chng. Th d 5: To trang CustomValidatorEx.aspx c s dng iu khin kim tra d liu nhp trong khung nhp phi l s chn, c ni dung di y :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CustomValidatorEx.aspx.cs" Inherits="CustomValidatorEx" %> <!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 runat="server"> <title>CustomValidator ServerValidate Example</title>

Lu hnh ni b

Trang 172

<script runat="server"> void ValidateBtn_OnClick(object sender, EventArgs e) { // Display whether the page passed validation. if (Page.IsValid) { Message.Text = "Page is valid."; } else { Message.Text = "Page is not valid!"; } } void ServerValidation(object source, ServerValidateEventArgs args) { try { // Test whether the value entered into the text box is even. int i = int.Parse(args.Value); args.IsValid = ((i%2) == 0); } catch(Exception ex) { args.IsValid = false; } } </script> </head> <body> <form id="form1" runat="server"> <div> <h3>CustomValidator ServerValidate Example</h3> <asp:Label id="Message" Text="Enter an even number:" Font-Names="Verdana" Font-Size="10pt" runat="server" AssociatedControlID="Text1"/> <br /> <asp:TextBox id="Text1" runat="server" /> &nbsp;&nbsp; <asp:CustomValidator id="CustomValidator1" ControlToValidate="Text1" Display="Static" ErrorMessage="Not an even number!" ForeColor="green" Font-Names="verdana" Font-Size="10pt" OnServerValidate="ServerValidation" runat="server"/> <br /> <asp:Button id="Button1"

Lu hnh ni b

Trang 173

Text="Validate" OnClick="ValidateBtn_OnClick" runat="server"/> </div> </form> </body> </html>

Giao din thit k trang CustomValidatorEx.aspx nh hnh sau:

Kt qu thc thi sau khi nhp gi tr trong khung nhp v click nt Validate, cho hai trng hp d liu nhp khng hp l v hp l.

5.6 iu khin ValidationSummary 1. ngha ValidationSummary cho php bn lit k tt c cc cc li kim tra trn trang t nhng iu khin validator vo mt v tr. iu khin ny c bit tin ch vi Form c rng ln. 2. Cch s dng Bn a iu khin ValidationSummary vo Form v thit lp cho n mt s thuc tnh sau: DisplayMode: Cho php bn ch r nh dng hin th li, n c th l cc gi tr nh BulletList, List, v SingleParagraph. HeaderText: Cho php bn hin th tiu tm tt cho cc li. ShowMessageBox: Qui nh bng thng bo li c c php hin th nh ca s MessageBox hay khng. Gi tr mc nh ca thuc tnh ny l False - khng hin th.

Thng bo li xut hin qua ca s MessageBox

Lu hnh ni b

Trang 174

ShowSummary: Qui nh bng thng bo li c c php hin th hay khng. Gi tr mc nh ca thuc tnh ny l True - c php hin th.

Thng bo li hin th trc tip trn trang Web

Th d 6: To trang ValidationSummaryEx.aspx c s dng mt s iu khin kim tra d liu trn trang, trong c iu khin ValidationSummary lit k tt c cc cc li kim tra trn trang t nhng iu khin kim chng vo mt v tr (cell <td>) thch hp.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidationSummaryEx.aspx.cs" Inherits="ValidationSummaryEx" %> <!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 runat="server"> <title>ValidationSummary Sample</title> </head> <body> <h3>ValidationSummary Sample</h3> <br /> <form id="form1" runat="server"> <div> <table cellpadding="10"> <tr> <td> <table style="background-color:#eeeeee; padding:10"> <tr> <td colspan="3"> <b>Credit Card Information</b> </td> </tr> <tr> <td align="right"> Card Type: </td> <td> <asp:RadioButtonList id="RadioButtonList1" RepeatLayout="Flow" runat="server"> <asp:ListItem>MasterCard</asp:ListItem> <asp:ListItem>Visa</asp:ListItem> </asp:RadioButtonList> </td>

Lu hnh ni b

Trang 175

<td align="center" rowspan="1"> <asp:RequiredFieldValidator id="RequiredFieldValidator1" ControlToValidate="RadioButtonList1" ErrorMessage="Card Type. " Display="Static" InitialValue="" Width="100%" runat="server"> * </asp:RequiredFieldValidator> </td> </tr> <tr> <td align="right"> Card Number: </td> <td> <asp:TextBox id="TextBox1" runat="server" /> </td> <td> <asp:RequiredFieldValidator id="RequiredFieldValidator2" ControlToValidate="TextBox1" ErrorMessage="Card Number. " Display="Static" Width="100%" runat="server"> * </asp:RequiredFieldValidator> </td> </tr> <tr> <td></td> <td> <asp:Button id="Button1" text="Validate" runat="server" /> </td> <td></td> </tr> </table> </td> <td valign="top"> <table cellpadding="20"> <tr> <td> <asp:ValidationSummary id="valSum" DisplayMode="BulletList" runat="server" HeaderText="You must enter a value in the following fields:" Font-Names="verdana" Font-Size="12"/>

Lu hnh ni b

Trang 176

</td> </tr> </table> </td> </tr> </table> </div> </form> </body> </html>

Giao din trang ValidationSummary.aspx nh hnh sau:

Kt qu thc thi cho hai trng hp d liu nhp khng hp l v hp l:

Th d 6: Minh ha s dng cc validation control To 1 trang ASP.Net tn DangKy.aspx vi giao din v iu kin rng buc nh sau :

Lu hnh ni b

Trang 177

Cc rng buc d liu c m t nh sau:


Tn ng nhp khng c b trng Tui phi nm trong khong t 18 n 40 Mt khu nhp phi chnh xc( nhp 2 ln). Email phi hp l(v d: abc@yahoo.com)

Bng m t cc thuc tnh ca cc controls


STT 1 2 3 4 5 6 7 8 9 10 11 12 Control Lable Lable Lable Lable Lable Lable TextBox TextBox TextBox TextBox TextBox RequiredFieldValidator Tn thuc tnh Text Text Text Text Text Text ID ID ID ID ID ControlToValidate ErrorMessage Gi tr thuc tnh Tn ng nhp Tui Mt khu Nhp li mt khu Email Thng bo txtTenDangNhap txtTuoi txtMatKhau txtNhapLaiMatKhau txtEmail txtTenDangNhap Bn phi nhp tn !

txtNhapLaiMatKhau Bn phi nhp li mt khu ! RangeValidator ControlToValidate txtTuoi ErrorMessage 18<= tui <=40 14 MaximumValue 40 MinimumValue 18 Type Integer 15 CompareValidator ControlToCompare txtNhapLaiMatKhau ControlToValidate txtMatKhau ErrorMessage Mt khu khng hp l 16 RegularExpression ErrorMessage Email khng hp l Validator ValidationExpresstion Nhp vo nt v chn Internet e-mail address. ControlToValidate txtEmail Sau khi chy trang DangKy.aspx, nu ta nhp vo gi tr khng hp l v nhn nt Kim Tra th s xut hin thng bo li tng ng nh hnh trn.

13

RequiredFieldValidator

ControlToValidate ErrorMessage

Lu hnh ni b

Trang 178

BI THC HNH CHNG 5 : Bi 1: Thc hnh li cc th d trong bi hc nm vng ni dung va hc. Bi 2: To mt ng dng ASP.NET thc hnh thao tc thit k trang bng m lnh. To trang RegularExpressionValidatorByCodePage.cs c ni dung sau:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RegularExpressionValidatorByCodePage.aspx.cs" Inherits="RegularExpressionValidatorByCodePage" %> <!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 runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> Valid format for phone number: xxx-xxx-xxxx<br /> </div> </form> </body> </html> Phn m lnh trang RegularExpressionValidatorByCodePage.aspx.cs public partial class RegularExpressionValidatorByCodePage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Label label = new Label(); label.Text = "Your phone:"; this.form1.Controls.Add(label); TextBox textBox = new TextBox(); textBox.ID = "Phone"; this.form1.Controls.Add(textBox); Button button = new Button(); button.Text = "OK"; this.form1.Controls.Add(button); RegularExpressionValidator regularExpressionValidator = new RegularExpressionValidator(); regularExpressionValidator.ControlToValidate = textBox.ID; regularExpressionValidator.ValidationExpression = @"((\(\d{3}\)?)|(\d{3}-))?\d{3}\d{4}"; regularExpressionValidator.Text="Invalid phone number"; this.form1.Controls.Add(regularExpressionValidator); } }

Trong phn ny thc hin to cc Web User Controls nh Label, TextBox, Button v RegularExpressionValidator v gn ln form. Kt qu thc thi trang RegularExpressionValidatorByCodePage.aspx: Lu hnh ni b Trang 179

Nhp d liu cho khung nhp phone sai nh dng , xut hin thong bo li.

Nhp d liu theo mu xxx-xxx-xxx l d liu hp l.

Bi 3: To mt ng dng ASP.NET thc hnh phn Validation Group To trang ValidationGroupsPage.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidationGroupsPage.aspx.cs" Inherits="ValidationGroupsPage" %> <!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 runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <div> Please enter your email to receive our letter:<br /> Email: <asp:TextBox ID="txtEmail" runat="server" ValidationGroup="letter"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="txtEmail" ValidationGroup="letter">Please enter your email</asp:RequiredFieldValidator><br /> &nbsp;<asp:Button ID="Button1" runat="server" PostBackUrl="~/ValidationGroups.aspx" Text="GO" ValidationGroup="letter" Width="50px" /><br /> -----------------------------------------------------------------<br /> Search:<br /> Keyword: <asp:TextBox ID="txtKeyword" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtKeyword" ErrorMessage="RequiredFieldValidator" SetFocusOnError="True">Please enter your email</asp:RequiredFieldValidator><br /> Certificate: <asp:DropDownList ID="ddlCertificate" runat="server" Width="115px"> <asp:ListItem></asp:ListItem> <asp:ListItem>B.A</asp:ListItem> <asp:ListItem>B.S</asp:ListItem> <asp:ListItem>M.B.A</asp:ListItem> <asp:ListItem>M.B.S</asp:ListItem>

Lu hnh ni b

Trang 180

</asp:DropDownList>&nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="ddlCertificate" ErrorMessage="RequiredFieldValidator">Please choose your certificate</asp:RequiredFieldValidator><br /> <asp:Button ID="Button2" runat="server" Text="GO" Width="50px" /></div> </div> </form> </body> </html>

Phn giao din thit k trang ValidationGroupsPage.aspx

Phn m lnh trang ValidationGroupsPage.aspx.cs


public partial class ValidationGroups : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { }

Kt qu thc thi: Trng hp 1 : Khi khng nhp d liu cho khung nhp Email, v click nt [GO] trn.

Nu nhp d liu, s khng c thng bo li. Trng hp 2: Khi khng nhp d liu cho khung nhp Keyword hoc Certificate, v click nt [GO] di.

Lu hnh ni b

Trang 181

Nu nhp d liu, s khng c thng bo li.

Lu hnh ni b

Trang 182

Chng 6: CC I TNG IU KHIN D LIU KHC (RICH CONTROLS LOGIN CONTROLS)


Cc vn chnh s c cp : Cc iu khin hin th cc trang khc nhau MultiView v Wizard. Cc iu khin trong nhm Login. Kt thc bi ny cc bn c th : Vn dng cc iu khin nng cao trn thit k trang ASP.NET theo yu cu ca ng dng. 6.1 iu khin hin th cc trang khc nhau MultiView iu khin MultiView cho php bn n hoc hin cc phn khc nhau ca trang Web, iu khin ny tin ch khi bn to mt TabPage. N thc s tin ch khi bn mun chia 1 trang web c di ln thnh cc phn hin th iu khin MultiView cha ng 1 hoc nhiu iu khin View, bn s dng Multiview la chn cc iu khin View trnh by. Cc thuc tnh: ActiveViewIndex: La chn iu khin View c a ra hin th bng ch s Index Views: Cho php bn ly v tp hp cc iu khin View cha ng trong iu khin MultiView. Cc phng thc: GetActiveView: Cho php ly v thng tin ca iu khin View c la chn. SetActiveView: cho php bn thit lp iu khin View c hin th. V MultiView h tr s kin sau: ActiveViewChanged: Xy ra khi iu khin View c la chn Cch s dng 1. Hin th nh mt TabPage Th d 1: Th d sau s hng dn bn to mt MultiView dng TabPage To trang MultiView1.aspx, gm c ba Button v mt MultiView. Sau , gn ba iu khin View vo trong MultiView, ni dung thit k trang nh sau:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultiView1.aspx.cs" Inherits="MultiView1" %> <!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 runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { font-size: x-large; }

Lu hnh ni b

Trang 183

.style2 { font-size: x-large; font-weight: bold; } </style> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Font-Bold="True" onclick="Button1_Click" Text="Panel One" /> <asp:Button ID="Button2" runat="server" Font-Bold="True" onclick="Button2_Click" Text="Panel Two" /> <asp:Button ID="Button3" runat="server" Font-Bold="True" onclick="Button3_Click" Text="Panel Three" /> <br /> <br /> <asp:MultiView ID="TabPageMultiView1" runat="server"> <asp:View ID="View1" runat="server"> <b><span class="style1">Content here (View1)....</span></b> </asp:View> <asp:View ID="View2" runat="server"> <b><span class="style1">Content here (View2)....</span></b> </asp:View> <asp:View ID="View3" runat="server"> <b><span class="style1">Content here (View3)....</span></b> </asp:View> </asp:MultiView> </div> </form> </body> </html>

Phn giao din thit k trang nh sau:

Phn m lnh thc thi trang MultiView1.aspx.cs:


public partial class MultiView1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e)

Lu hnh ni b

Trang 184

{ TabPageMultiView1.SetActiveView(View1); } protected void Button1_Click(object sender, EventArgs e) { TabPageMultiView1.SetActiveView(View1); } protected void Button2_Click(object sender, EventArgs e) { TabPageMultiView1.SetActiveView(View2); } protected void Button3_Click(object sender, EventArgs e) { TabPageMultiView1.SetActiveView(View3); } }

Kt qu thc thi chng trnh: Trang hin th ln u:

Click nt [Panel Two], chuyn sang View2.

Click nt [Panel Three], chuyn sang View3.

2. Hin th nhiu phn trn trang. Bn c th chia mt Form c di ln thnh cc thnh phn nh hn v hin th tng phn, bn c th s dng cc iu khin Button nm trong iu khin MultiView v khi Button c nhn th Multiview s x l thay i hin th View khc. iu khin MultiView h tr cc iu khin lnh sau: NextView: MultiView s kch hot iu khin View tip theo PrevView: MultiView s kch hot iu khin View trc SwitchViewByID: MultiView s kch hot View ch nh bi i s ca iu khin Button SwitchViewByIndex: MultiView s kch hot View ch nh bi i s ca iu khin Button Th d 2: Th d sau s hng dn bn to mt Form c nhiu phn vi vic s dng iu khin lnh NextView. Phn ni dung trang MultiView2.aspx, thit k mt trong MultiView c bn iu khin View, v trong mi View s c cc Button tng ng thc hin vic i ti Lu hnh ni b Trang 185

OnClick="NextButton_Command" hoc quay lui OnClick="BackButton_Command" qua li cc

View.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultiView2.aspx.cs" Inherits="MultiView2" %> <!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 runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <h3> Th d MuiltiView</h3> <asp:Panel id="Page_1ViewPanel" Width="288px" Height="60px" HorizontalAlign =Left Font-size="12" BackColor="#C0C0FF" BorderColor="#404040" BorderStyle="Double" runat="Server"> <asp:MultiView id="MultiView" ActiveViewIndex=0 runat="Server"> <asp:View id="Page_1" runat="Server"> <asp:Label id="Page_1Label" Font-bold="True" Text="Loi ng dng m bn ang pht trin l g?" runat="Server"></asp:Label><br><br><br /> <asp:RadioButton id="Page_1Radio1" Text="Winform" Checked="False" GroupName="RadioGroup1" runat="server" > </asp:RadioButton><br> <asp:RadioButton id="Page_1Radio2" Text="WebForm" Checked="False" GroupName="RadioGroup1" runat="server" > </asp:RadioButton><br><br> <asp:Button id="Page_1Next" Text = "Tip tc" OnClick="NextButton_Command" Height="25" Width="70" runat= "Server"> </asp:Button> </asp:View>

Lu hnh ni b

Trang 186

<asp:View id="Page2" runat="Server"> <asp:Label id="Page2Label" Font-bold="True" Text="Kinh nghim bao lu ri?" runat="Server"></asp:Label><br /><br/><br/><br /> <asp:RadioButton id="Page2Radio1" Text="Gn 5 Nm" Checked="False" GroupName="RadioGroup1" runat="Server"> </asp:RadioButton><br> <asp:RadioButton id="Page2Radio2" Text="Hn 5 nm" Checked="False" GroupName="RadioGroup1" runat="Server"> </asp:RadioButton><br><br> <asp:Button id="Page2Back" Text = "Li li" OnClick="BackButton_Command" Height="25" Width="70" runat= "Server"> </asp:Button> <asp:Button id="Page2Next" Text = "Tip tc" OnClick="NextButton_Command" Height="25" Width="70" runat="Server"> </asp:Button> </asp:View> <asp:View id="Page3" runat="Server"> <asp:Label id="Page3Label1" Font-bold="True" Text= "Ngn ng s dng chnh l g ?" runat="Server"></asp:Label><br><br><br /><br /> <asp:RadioButton id="Page3Radio1" Text="Visual Basic .NET" Checked="False" GroupName="RadioGroup1" runat="Server"> </asp:RadioButton><br> <asp:RadioButton id="Page3Radio2" Text="C#" Checked="False" GroupName="RadioGroup1" runat="Server"> </asp:RadioButton><br>

Lu hnh ni b

Trang 187

<asp:RadioButton id="Page3Radio3" Text="C++" Checked="False" GroupName="RadioGroup1" runat="Server"> </asp:RadioButton><br><br> <asp:Button id="Page3Back" Text = "Li li" OnClick="BackButton_Command" Height="25" Width="70" runat="Server"> </asp:Button> <asp:Button id="Page3Next" Text = "Tip theo" OnClick="NextButton_Command" Height="25" Width="70" runat="Server"> </asp:Button></asp:View> <asp:View id="Page4" runat="Server"> <asp:Label id="Label1" Font-bold="True" Text = "Xin chn thnh cm n bn." runat="Server"></asp:Label><br /> <br /> <br><br> <asp:Button id="Page4Save" Text = "Lu li" OnClick="NextButton_Command" Height="25" Width="110" runat="Server"> </asp:Button> <asp:Button id="Page4Restart" Text = "Lm li" OnClick="BackButton_Command" Height="25" Width="110" runat= "Server"> </asp:Button> </asp:View> </asp:MultiView> </asp:Panel> </div> </form> </body> </html>

Phn giao din thit k trang MultiView2.aspx:

Lu hnh ni b

Trang 188

Phn m lnh thc thi trang MultiView2.aspx.cs:


public partial class MultiView2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void NextButton_Command(object sender, EventArgs e) { if (MultiView.ActiveViewIndex > -1 & MultiView.ActiveViewIndex < 3) { MultiView.ActiveViewIndex += 1; } else if (MultiView.ActiveViewIndex == 3) { Page4Save.Enabled = false; Page4Restart.Enabled = false; } else { throw new Exception("An error occurred."); } } protected void BackButton_Command(object sender, EventArgs e) { if (MultiView.ActiveViewIndex > 0 & MultiView.ActiveViewIndex <= 2) { MultiView.ActiveViewIndex -= 1; }

Lu hnh ni b

Trang 189

else if (MultiView.ActiveViewIndex == 3) { MultiView.ActiveViewIndex = 0; } else { throw new Exception("An error occurred."); } } }

Kt qu thc hin :

6.2 iu khin Wizard iu khin Wizard ging vi iu khin MultiView c th dng chia mt Form ln thnh nhiu phn nh. Tuy nhin n s c thm mt s thuc tnh m MultiView khng h tr. iu khin Wizard c th cha nhiu iu khin WizardStep con, nhng ch 1 WirardStep c hin th ti 1 thi im. Cc thuc tnh. ActiveStep: cho php bn ly thng tin ca WizardStep ang kch hot ActiveStepIndex: cho php bn gn hoc ly v ch s Index ca WizardStep ang kch hot CancelDestinationPageUrl: cho php bn ch r a ch URL c gi ti khi ngi s dng nhn nt Cancel DisplayCancelButton: Cho php n hoc hin Cancel Button. DisplaySlideBar: Cho php n hoc hin SlideBar(hin th tt c cc WizardStep) Lu hnh ni b Trang 190

FinishDestinationPageUrl: cho php bn ch nh a ch URL c gi ti khi ngi dng nhn nt Finish HeaderText: cho php bn ch nh tiu hin th trn nh ca iu khin Wizard. WizadSteps: Cho php bn ly thng tin ca cc iu khin WizardStep trong iu khin Wizard iu khin Wizard h tr cc Template. FinishNavigationTemplate: cho php hin th Navigation bc kt thc HeaderTemplate: hin th thanh tiu u ca iu khin Wizard SlideBarTemplate: Cho php hin th SlideBar trong iu khin Wizard StartNavigationTemplate: cho php hin th Navigation bc bt u StepNavigationTemplate: cho php hin th Navigation cc bc khng phi bc bt u v kt thc. iu khin Wizard h tr cc phng thc: GetHistory(): cho php ly thng tin ca cc iu khin Wizard m truy cp. GetStepType(): Cho php bn tr v kiu ca mi WizardStep ring theo ch s, n c th l cc thuc tnh sau: Auto, Start, Finish hay Step MoveTo(): cho php bn di chuyn n mt WizardStep. iu khin Wizard h tr cc s kin: ActiveStepChanged: xy ra khi mt WizardStep tr thnh Step c kch hot CancelButtonClick: xy ra khi Cancel Button c nhn. FinishButtonClick: xy ra khi Finish Button c nhn NextButtonClick: Xy ra khi Next button c nhn PreviousButtonClick: xy ra khi Previous button c nhn SlideBarButtonClick: xy ra khi SlideBar button c nhn: Mt iu khin Wizard cha ng mt hoc nhiu WizardStep din t cc bc trong qu trnh Wizard. Cc WizardStep h tr cc thuc tnh: AllowReturn: Ngn cn hay cho php ngi s dng tr v bc ny t mt bc khc. Name: tn ca iu khin WirardStep StepType:Cho php bn gn hay ly v kiu ca WirardStep n c th l cc gi tr sau: Auto, Finish, Start, Complete v Step. Title: ly v hoc gn tiu ca iu khin WizardStep tiu ny c hin th Wizard Slidebar Wizard: cho php bn ly thng tin iu khin Wizard cha trong WizardStep. Cc s kin trong WizardStep Activate: Xy ra khi mt WizardStep c kch hot DeActivate: xy ra khi WizardStep khc c kch hot. StepType l thuc tnh quan trng nht ca Wizard, thuc tnh no xc nh WizardStep c a ra nh th no, mc nh l Auto

Lu hnh ni b

Trang 191

Th d 3: To trang ASP.NET c s dng iu khin Wizard v c ba WizardStep bn trong c xy dng nh sau:

Phn m lnh Wizard ban u cha cc WizardStep :


<asp:Wizard ID="Wizard1" runat="server" ActiveStepIndex="0" FinishCompleteButtonText="Kt thc" FinishPreviousButtonText="Tr li" Height="155px" StartNextButtonText="ng " StepNextButtonText="Tip theo" StepPreviousButtonText="V trc" Width="491px"> <WizardSteps> </WizardSteps> </asp:Wizard>

Thc hin vic thm cc WizardStep, chn Add/Remove WizardSteps

Thit k giao din cho WizardStep- [Bc 1]

Lu hnh ni b

Trang 192

M lnh Thit k giao din WizardStep- [Bc 1]


<asp:WizardStep runat="server" Title="Bc 1"> <strong>Bn ng cc ni quy khi gia nhp thnh vin.<br /> Bn khng c s dng ti khon ng ti sai mc ch.<br /> </strong> </asp:WizardStep>

Thit k giao din WizardStep- [Bc 2]

M lnh Thit k giao din WizardStep- [Bc 2]


<asp:WizardStep runat="server" Title="Bc 2"> &nbsp;<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" CreateUserButtonText="ng k&#253;"> <WizardSteps> <asp:CreateUserWizardStep runat="server"> <ContentTemplate> <table border="0"> <tr> <td align="center" colspan="2" style="height: 20px"> To ti khon mi.</td> </tr> <tr> <td align="right">

Lu hnh ni b

Trang 193

<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Tn ng nhp:</asp:Label></td> <td> <asp:TextBox ID="UserName" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="right"> <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Mt khu:</asp:Label></td> <td> <asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox> <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="right"> <asp:Label ID="ConfirmPasswordLabel" runat="server" AssociatedControlID="ConfirmPassword">G li mt khu:</asp:Label></td> <td> <asp:TextBox ID="ConfirmPassword" runat="server" TextMode="Password"></asp:TextBox> <asp:RequiredFieldValidator ID="ConfirmPasswordRequired" runat="server" ControlToValidate="ConfirmPassword" ErrorMessage="Confirm Password is required." ToolTip="Confirm Password is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="right"> <asp:Label ID="EmailLabel" runat="server" AssociatedControlID="Email">E-mail:</asp:Label></td> <td> <asp:TextBox ID="Email" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="EmailRequired" runat="server" ControlToValidate="Email" ErrorMessage="E-mail is required." ToolTip="E-mail is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="right">

Lu hnh ni b

Trang 194

<asp:Label ID="QuestionLabel" runat="server" AssociatedControlID="Question">Cu hi bo mt:</asp:Label></td> <td> <asp:TextBox ID="Question" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="QuestionRequired" runat="server" ControlToValidate="Question" ErrorMessage="Security question is required." ToolTip="Security question is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="right"> <asp:Label ID="AnswerLabel" runat="server" AssociatedControlID="Answer">Tr li cu hi bo mt:</asp:Label></td> <td> <asp:TextBox ID="Answer" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="AnswerRequired" runat="server" ControlToValidate="Answer" ErrorMessage="Security answer is required." ToolTip="Security answer is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="center" colspan="2" style="height: 21px"> <asp:CompareValidator ID="PasswordCompare" runat="server" ControlToCompare="Password" ControlToValidate="ConfirmPassword" Display="Dynamic" ErrorMessage="Bn nhp li mt khu b sai. " ValidationGroup="CreateUserWizard1"></asp:CompareValidator> </td> </tr> <tr> <td align="center" colspan="2" style="color: red"> <asp:Literal ID="lrlLoi" runat="server" EnableViewState="False"></asp:Literal> </td> </tr> </table> </ContentTemplate> </asp:CreateUserWizardStep> <asp:CompleteWizardStep runat="server"> </asp:CompleteWizardStep> </WizardSteps> </asp:CreateUserWizard> </asp:WizardStep>

Thit k giao din WizardStep- [Bc 3]

Lu hnh ni b

Trang 195

M lnh Thit k giao din WizardStep- [Bc 3]


<asp:WizardStep runat="server" Title="Bc 3"> Bn ng k thnh cng.<br /> Xin chn thnh cm n.</asp:WizardStep>

Phn m lnh trang:


public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) }

Kt qu thc thi: Bc 1:

Click [ng ] chuyn sang [Bc 2],

Lu hnh ni b

Trang 196

Click [ng k] sau Click [Tip theo] chuyn sang [Bc 3]

Click nt [Kt thc] kt thc thc thi ng dng. nh dng hin th Wizard theo AutoFormat..

6.3 Nhm iu khin Login Bn c th s dng cc iu khin Login ca ASP.NET xy dng cc h thng ng k ngi s dng cho wensite ca mnh, Bn c th s dng cc Login Control to form ng nhp, ng k, thay i mt khu hay ghi nh mt khu trn Form. Bao gm cc iu khin: Login: Cho php hin th Form ng nhp ngi s dng. CreateUserWizard: Cho php hin th Form ng k ngi s dng. LoginStatus: Hin th trng thi Login hay Logout ph thuc vo trng thi kim chng ngi s dng. LoginName: Hin th tn ngi ng k hin ti. ChangePassword: Hin th Form cho php ngi s dng thay i mt khu. PasswordRecovery: Cho php ngi s dng khi phc password, password ny s c gi vo mail cho ngi s dng. LoginView: hin th cc ni dung khc nhau ti mi ngi s dng phc thuc thuc vo authentication hoc role. Trong phn ny chng ta s hc chi tit cc iu khin: Login: Cho php hin th Form ng nhp ngi s dng. CreateUserWizard: Cho php hin th Form ng k ngi s dng. Cc iu khin cn li s cp trong chng Bo mt ASP.NET Lu hnh ni b Trang 197

Hnh 6. : Nhm iu khin Login. iu khin Login iu khin Login a ra mt form ng nhp tiu chun. Mc nh iu khin Login s dng ASP.NET MenberShip kim chng ngi s dng, tuy nhin bn c th ty chnh kiu kim chng ngi s dng vi iu khin Login. iu khin Login h tr rt nhiu thuc tnh cho php bn ty chnh cch hin th v ng x ca iu khin. Cc thuc tnh ca iu khin <asp:Login>
<asp:Login ID="Login1" // tn i tng runat="server" // Phn ni dung Text InstructionText="Please enter your own username and password" TitleText="Login" ToolTip="Login" TextLayout="TextOnTop" LoginButtonText="Login" RememberMeText="Remember me for next time." // Phn to user mi CreateUserUrl="~/CreateNewUserPage.aspx" CreateUserIconUrl="~/Images/NEW.bmp" CreateUserText="Signup? " // Phn phc hi/to mi li password PasswordRecoveryUrl="~/ForgotPasswordPage.aspx" PasswordRecoveryIconUrl="~/Images/VIEW.BMP" PasswordRecoveryText="Forget your ID or password?" // Phn tr gip HelpPageUrl="~/Help.aspx" HelpPageIconUrl="~/Images/HELP.BMP" HelpPageText="Help" //Cc s kin chnh OnAuthenticate="Login1_Authenticate" OnLoad="Login1_Load" .. </asp:Login>

Phn giao din thit k trang LoginControl.aspx:

Lu hnh ni b

Trang 198

Phn m lnh thit k trang LoginControl.aspx:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LoginPage.aspx.cs" Inherits="LoginPage" %> <!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 runat="server"> <title>Untitled Page</title></head> <body> <form id="form1" runat="server"> <div> <asp:Login ID="Login1" runat="server" CreateUserUrl="~/CreateNewUserPage.aspx" HelpPageUrl="~/Help.aspx" InstructionText="Please enter your own username and password" LoginButtonText="Login" PasswordRecoveryUrl="~/ForgotPasswordPage.aspx" RememberMeText="Remember me for next time." Width="431px" CreateUserIconUrl="~/Images/NEW.bmp" CreateUserText="Signup? " OnAuthenticate="Login1_Authenticate" PasswordRecoveryIconUrl="~/Images/VIEW.BMP" PasswordRecoveryText="Forget your ID or password?" TitleText="Login" ToolTip="Login" HelpPageIconUrl="~/Images/HELP.BMP" HelpPageText="Help" OnLoad="Login1_Load" EnableTheming="True" BackColor="#E3EAEB" BorderColor="#E6E2D8" BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#333333" TextLayout="TextOnTop" Height="238px" style="font-weight: 700; font-size: large"> <TitleTextStyle Font-Bold="True" Font-Underline="True" HorizontalAlign="Left" BackColor="#1C5E55" Font-Size="0.9em" ForeColor="White" /> <InstructionTextStyle HorizontalAlign="Left" Font-Italic="True" ForeColor="Black" /> <TextBoxStyle Font-Size="0.8em" /> <LoginButtonStyle BackColor="White" BorderColor="#C5BBAF" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#1C5E55" /> </asp:Login> </div> </form>

Lu hnh ni b

Trang 199

</body> </html>

Phn m lnh x l trang LoginControl.aspx.cs:


public partial class LoginPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.Login1.UserName="annguyen@gmail.com"; } protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) { if(Login1.UserName==" annguyen@gmail.com ") { Response.Redirect("Default.aspx"); } else Login1.FailureText="Oh ! Sai roi a nha."; } protected void Login1_Load(object sender, EventArgs e) { this.Login1.DisplayRememberMe= false; } }

Kt qu thc thi:

Chuyn sang trang Default.aspx khi click nt [Login]

Lu hnh ni b

Trang 200

Nhp sai a ch email (khng phi chui annguyen@gmail.com) s in thng bo li:

iu khin CreateUserWizard Khi click link Signup, s chuyn sang trang CreateNewUserPage.aspx do CreateUserUrl="~/CreateNewUserPage.aspx" . Trang ny cho php bn to mi mt user vi mt s thng tin yu cu bt buc phi nhp. y l iu khin dng Wizard nn cng s c cc bc WizardStep v mt s cc thuc tnh sau:
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" AutoGeneratePassword="True" DisableCreatedUser="True" \\ Hin nt Cancel DisplayCancelButton="True" <!s kin chnh --> OnCreatingUser="CreateUserWizard1_CreatingUser" OnLoad="CreateUserWizard1_Load" <!-- c hai bc WizardStep --> <WizardSteps> <asp:CreateUserWizardStep runat="server"> </asp:CreateUserWizardStep> <asp:CompleteWizardStep runat="server"> </asp:CompleteWizardStep> </WizardSteps> <!quy nh cc Style --> <SideBarStyle BackColor="#5D7B9D" BorderWidth="0px" Font-Size="0.9em" VerticalAlign="Top" /> <SideBarButtonStyle BorderWidth="0px" Font-Names="Verdana" ForeColor="White" /> <ContinueButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" ForeColor="#284775" /> <NavigationButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" ForeColor="#284775" /> <HeaderStyle BackColor="#5D7B9D" BorderStyle="Solid" Font-Bold="True" FontSize="0.9em" ForeColor="White" HorizontalAlign="Center" /> <CreateUserButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" ForeColor="#284775" /> <TitleTextStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <StepStyle BorderWidth="0px" />

Lu hnh ni b

Trang 201

</asp:CreateUserWizard>

Phn giao din thit k trang CreateNewUserPage.aspx:

Phn m lnh thc thi trang CreateNewUserPage.aspx.cs


public partial class CreateNewUserPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void CreateUserWizard1_CreatingUser(object sender, LoginCancelEventArgs e) { Response.Redirect("LoginPage.aspx"); } protected void CreateUserWizard1_Load(object sender, EventArgs e) this.CreateUserWizard1.UserName = "annguyen"; this.CreateUserWizard1.Email = "annguyen@gmail.com"; } } {

Kt qu thc thi :

Click nt [Create User] s quay li trang LoginPage.aspx.


protected void CreateUserWizard1_CreatingUser(object sender, LoginCancelEventArgs e) { Response.Redirect("LoginPage.aspx"); }

Lu hnh ni b

Trang 202

BI TP CHNG 6: Bi 1: Thc hnh li cc th d trong bi hc nm vng ni dung va hc. Bi 2: To mt ng dng ASP.NET thc hnh vi MultiView to mt thip chc mng. To trang MultiViewGreetingCardMaker.aspx c dng sau:

Phn m lnh thit k trang MultiViewGreetingCardMaker.aspx:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultiViewGreetingCardMaker.aspx.cs" Inherits="MultiViewGreetingCardMaker" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server">

Lu hnh ni b

Trang 203

<div> <table border="1" cellpadding="5"> <tr valign="top"> <td style="width: 281px"> <asp:MultiView id="MultiView1" runat="server" ActiveViewIndex="0"> <asp:View ID="View1" runat="server"> Choose a foreground (text) color:<br /> <asp:DropDownList ID="lstForeColor" runat="server" AutoPostBack="True" Height="22px" OnSelectedIndexChanged="ControlChanged" Width="194px"> </asp:DropDownList><br /> <br /> Choose a background color:<br /> <asp:DropDownList ID="lstBackColor" runat="server" AutoPostBack="True" Height="22px" OnSelectedIndexChanged="ControlChanged" Width="194px"> </asp:DropDownList> <br /> <asp:Button ID="cmdNext" runat="server" Text="Next >" CommandName="NextView" /> </asp:View> <asp:View ID="View2" runat="server"> Choose a border style:<br /> <asp:RadioButtonList ID="lstBorder" runat="server" AutoPostBack="True" Height="59px" OnSelectedIndexChanged="ControlChanged" RepeatColumns="2" Width="177px"> </asp:RadioButtonList><br /> <br /> <asp:CheckBox ID="chkPicture" runat="server" AutoPostBack="True" OnCheckedChanged="ControlChanged" Text="Add the Default Picture" /> <br /> <asp:Button ID="Button3" runat="server" Text="< Prev" CommandName="PrevView" /> <asp:Button ID="Button4" runat="server" Text="Next >" CommandName="NextView" /> </asp:View> <asp:View ID="View3" runat="server"> Choose a font name:<br /> <asp:DropDownList ID="lstFontName" runat="server" AutoPostBack="True" Height="22px" OnSelectedIndexChanged="ControlChanged" Width="194px"> </asp:DropDownList><br /> <br /> Specify a font size:<br /> <asp:TextBox ID="txtFontSize" runat="server" AutoPostBack="True" OnTextChanged="ControlChanged"></asp:TextBox><br /> <br /> Enter the greeting text below:<br /> <asp:TextBox ID="txtGreeting" runat="server" Height="85px" OnTextChanged="ControlChanged"

Lu hnh ni b

Trang 204

TextMode="MultiLine" Width="240px" AutoPostBack="True"></asp:TextBox> <br /> <asp:Button ID="Button1" runat="server" Text="< Prev" CommandName="PrevView" /> <asp:Button ID="Button2" runat="server" Text="Apply" /> </asp:View> </asp:MultiView> </td> <td > <asp:Panel ID="pnlCard" runat="server" Height="445px" HorizontalAlign="Center" Style="z-index: 101; " Width="339px"> <br /> &nbsp; <asp:Label ID="lblGreeting" runat="server" Height="150px" Width="272px"></asp:Label> <asp:Image ID="imgDefault" runat="server" Height="160px" Visible="False" Width="212px" /> </asp:Panel> </td> </tr> </table> </div> </form> </body> </html>

Phn m lnh thc thi trang MultiViewGreetingCardMaker.aspx.cs:


public partial class MultiViewGreetingCardMaker : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { // Get the list of colors. string[] colorArray = Enum.GetNames(typeof(System.Drawing.KnownColor)); lstBackColor.DataSource = colorArray; lstBackColor.DataBind(); lstForeColor.DataSource = colorArray; lstForeColor.DataBind(); lstForeColor.SelectedIndex = 34; lstBackColor.SelectedIndex = 163; // Get the list of available fonts and add them to the font list. System.Drawing.Text.InstalledFontCollection fonts; fonts = new System.Drawing.Text.InstalledFontCollection(); foreach (FontFamily family in fonts.Families) {

Lu hnh ni b

Trang 205

lstFontName.Items.Add(family.Name); } // Set border style options. string[] borderStyleArray = Enum.GetNames(typeof(BorderStyle)); lstBorder.DataSource = borderStyleArray; lstBorder.DataBind(); // Select the first border option. lstBorder.SelectedIndex = 0; // Set the picture. imgDefault.ImageUrl = "defaultpic.png"; } } private void Update() { // Update the color. pnlCard.BackColor = Color.FromName(lstBackColor.SelectedItem.Text); lblGreeting.ForeColor = Color.FromName(lstForeColor.SelectedItem.Text); // Update the font. lblGreeting.Font.Name = lstFontName.SelectedItem.Text; try { if (Int32.Parse(txtFontSize.Text) > 0) { lblGreeting.Font.Size = FontUnit.Point(Int32.Parse(txtFontSize.Text)); } } catch { // Ignore invalid value. } try { if (Int32.Parse(txtFontSize.Text) > 0) { lblGreeting.Font.Size = FontUnit.Point(Int32.Parse(txtFontSize.Text)); } } catch { // Ignore invalid value. } // Find the appropriate TypeConverter for the BorderStyle enumeration. TypeConverter cnvrt = TypeDescriptor.GetConverter(typeof(BorderStyle)); // Update the border style using the value from the converter.

Lu hnh ni b

Trang 206

pnlCard.BorderStyle = (BorderStyle)cnvrt.ConvertFromString( lstBorder.SelectedItem.Text);

// Update the picture. if (chkPicture.Checked == true) { imgDefault.Visible = true; } else { imgDefault.Visible = false; } // Set the text. lblGreeting.Text = txtGreeting.Text; } protected void ControlChanged(Object sender, EventArgs e) { // Refresh the greeting card. Update(); } }

Kt qu thc thi:

Chn gi tr xong, click [Next]

Lu hnh ni b

Trang 207

Chn gi tr xong, click nt [Next].

Chn gi tr xong, click nt [Apply] Bi 3: To mt ng dng ASP.NET thc hnh vi Wizard to mt thip chc mng nh trn. To trang c s dng iu khin Wizard c cc WizardStep c thit k nh sau: [Step 0 Hello]

Lu hnh ni b

Trang 208

[Step 1 Colors]

[Step 2 - Background]

[Step 3 - Text]

Lu hnh ni b

Trang 209

[Greeting Card]

Phn m lnh thit k trang WizardGreetingCardMaker.aspx:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WizardGreetingCardMaker.aspx.cs" Inherits="WizardGreetingCardMaker" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Greeting Card Wizard</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server">

Lu hnh ni b

Trang 210

<div> <asp:Wizard ID="Wizard1" runat="server" ActiveStepIndex="4" BackColor="LemonChiffon" BorderStyle="Groove" BorderWidth="2px" CellPadding="10" OnFinishButtonClick="Wizard1_FinishButtonClick" Width="456px"> <WizardSteps> <asp:WizardStep runat="server" Title="Step 0 - Hello"> Hello Asp.net</asp:WizardStep> <asp:WizardStep runat="server" Title="Step 1 - Colors"> Choose a foreground (text) color:<br /> <asp:DropDownList ID="lstForeColor" runat="server" Width="194px"> </asp:DropDownList><br /> <br /> Choose a background color:<br /> <asp:DropDownList ID="lstBackColor" runat="server" Width="194px"> </asp:DropDownList> </asp:WizardStep> <asp:WizardStep runat="server" Title="Step 2 - Background"> Choose a border style:<br /> <asp:RadioButtonList ID="lstBorder" runat="server" Height="59px" RepeatColumns="2" Width="177px"> </asp:RadioButtonList><br /> <br /> <asp:CheckBox ID="chkPicture" runat="server" Text="Add the Default Picture" /> </asp:WizardStep> <asp:WizardStep runat="server" Title="Step 3 - Text"> Choose a font name:<br /> <asp:DropDownList ID="lstFontName" runat="server" Width="194px"> </asp:DropDownList><br /> <br /> Specify a font size:<br /> <asp:TextBox ID="txtFontSize" runat="server" ></asp:TextBox><br /> <br /> Enter the greeting text below:<br /> <asp:TextBox ID="txtGreeting" runat="server" TextMode="MultiLine" Width="240px" ></asp:TextBox> </asp:WizardStep> <asp:WizardStep runat="server" StepType="Complete" Title="Greeting Card"> <asp:Panel ID="pnlCard" runat="server" Height="445px" HorizontalAlign="Center" Style="z-index: 101; " Width="339px"> <br /> &nbsp; <asp:Label ID="lblGreeting" runat="server" Height="150px" Width="272px"></asp:Label>

Lu hnh ni b

Trang 211

<asp:Image ID="imgDefault" runat="server" Height="160px" Visible="False" Width="212px" /></asp:Panel> </asp:WizardStep> </WizardSteps> </asp:Wizard> </div> </form> </body> </html>

Phn m lnh thc thi trang WizardGreetingCardMaker.aspx.cs:


public partial class WizardGreetingCardMaker : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { // Get the list of colors. string[] colorArray = Enum.GetNames(typeof(System.Drawing.KnownColor)); lstBackColor.DataSource = colorArray; lstBackColor.DataBind(); lstForeColor.DataSource = colorArray; lstForeColor.DataBind(); lstForeColor.SelectedIndex = 34; lstBackColor.SelectedIndex = 163; // Get the list of available fonts and add them to the font list. System.Drawing.Text.InstalledFontCollection fonts; fonts = new System.Drawing.Text.InstalledFontCollection(); foreach (FontFamily family in fonts.Families) { lstFontName.Items.Add(family.Name); } // Set border style options. string[] borderStyleArray = Enum.GetNames(typeof(BorderStyle)); lstBorder.DataSource = borderStyleArray; lstBorder.DataBind(); // Select the first border option. lstBorder.SelectedIndex = 0; // Set the picture. imgDefault.ImageUrl = "defaultpic.png"; } } protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e) { Update(); }

Lu hnh ni b

Trang 212

private void Update() { // Update the color. pnlCard.BackColor = Color.FromName(lstBackColor.SelectedItem.Text); lblGreeting.ForeColor = Color.FromName(lstForeColor.SelectedItem.Text); // Update the font. lblGreeting.Font.Name = lstFontName.SelectedItem.Text; try { if (Int32.Parse(txtFontSize.Text) > 0) { lblGreeting.Font.Size = FontUnit.Point(Int32.Parse(txtFontSize.Text)); } } catch { // Ignore invalid value. } try { if (Int32.Parse(txtFontSize.Text) > 0) { lblGreeting.Font.Size = FontUnit.Point(Int32.Parse(txtFontSize.Text)); } } catch { // Ignore invalid value. } // Find the appropriate TypeConverter for the BorderStyle enumeration. TypeConverter cnvrt = TypeDescriptor.GetConverter(typeof(BorderStyle)); // Update the border style using the value from the converter. pnlCard.BorderStyle = (BorderStyle)cnvrt.ConvertFromString( lstBorder.SelectedItem.Text);

// Update the picture. if (chkPicture.Checked == true) { imgDefault.Visible = true; } else { imgDefault.Visible = false; } // Set the text. lblGreeting.Text = txtGreeting.Text;

Lu hnh ni b

Trang 213

} }

Kt qu thc thi trang WizardGreetingCardMaker.aspx:

Chn gi tr xong, click nt [Next].

Chn gi tr xong, click nt [Next].

Chn gi tr xong, click nt [Next].

Lu hnh ni b

Trang 214

Chn gi tr xong, click nt [Finish].

Lu hnh ni b

Trang 215

Chng 7:

GII THIU ADO.NET

Cc vn chnh s c cp : Kin trc ADO.NET. Cc i tng trong ADO.NET: Connected Layer (Connection, Command, DataReader, DataAdapter) v Disconnected Layer(DataSet, DataTable, DataRow, DataColumn, DataRelation). i tng SqlDataSource. Kt thc chng ny cc bn c th : Trnh by c kin trc ADO.Net . M t v s dng i tng trong ADO.NET trong ng dng ASP.NET S dng i tng SqlDataSource. 7.1 Kin trc ADO.NET ADO.NET l mt phn ca .NET Framework, c xem l b th vin lp chu trch nhim x l d liu trong ngn ng MS .NET. ADO.NET gm hai thnh phn chnh cho vic truy xut v iu khin d liu l cc trnh cung cp d liu .NET Framework (.NET Framework Data Provider) v DataSet. M hnh di y minh ha mi quan h gia trnh cung cp d liu ca .NET Framework v DataSet.

Hnh 7. 1: Kin trc ADO.NET. Nhn chung vic kt ni gia ng dng v c s d liu (CSDL) thng qua ADO.NET theo hai hng: Connected Layer: c ch ny yu cu phi thc hin kt ni vi Database trong khi ang thc hin cc thao tc vi d liu. Cc i tng ca c ch ny l: o Connection: i tng qun l ng/m kt ni ti Database. o Command: i tng thc hin cc cu lnh tng tc truy vn, rt trch d liu t database sau khi thit lp kt ni ti d liu v tr v kt qu. Lu hnh ni b Trang 216

o DataReader: i tng x l c d liu tu CSDL. o DataAdapter: y l i tng rt quan trng ca ADO.NET, l cu ni ca Database v Dataset (Dataset l i tng ngt kt ni), bi v i tng ngt kt ni Dataset khng th tng tc trc tip vi Database nn cn mt i tng trung gian ly d liu t Database. V chnh l DataAdapter. V DataAdpater khi thao tc vi Database vn phi duy tr kt ni nn n c lit k vo dng kt ni, nhng bn cht phc v cho vic ngt kt ni. Disconnected Layer : ch c mt i tng chu trch nhim ngt kt ni chnh l DataSet. Nhim v ca DataSet l nhn d liu v t DataAdapter v x l n. DataSet c th c xem nh mt Database trong b nh gm tt c cc bng, quan h.. DataSet c nhiu i tng c xem l con nh: DataTable, cp thp hn ca DataTable c cc i tng DataRow, DataColumn, DataRelation. Ngoi ra cn c cc i tng nhm: v d: DataTableCollection, DataRowCollection, DataColumnCollection. Vic s dng DataSet l mt tin b ln ca kin trc ADO.NET.

Nh vy c th nhn mt cch tng qut nh sau:

Application Disconnected Access Connected Access DataSet

.NET Data Provider

XML Data

DataBase
Hnh 7. 2: C ch kt ni ADO.NET 7.2 Tm hiu trnh cung cp d liu ca ADO.NET ADO.NET h tr nhiu trnh cung cp d liu, mi trnh cung cp tng tc vi mt DBMS c th. Li ch u tin ca phng php ny l mt trnh cung cp d liu c th c th c lp trnh truy xut n bt c thuc tnh no ca mt DBMS m c ch nh bi trnh cung cp . Li ch khc l trnh cung cp d liu c th kt ni ngay lp tc n CSDL m khng thng qua tng nh x trung gian (trnh iu khin) gia cc lp.(Hnh 7.3).

Lu hnh ni b

Trang 217

ADO.NET Data Objects

Managed Code

SQL Server Data Provider

OLE DB Data Provider

Oracle Data Provider

ODBC Data Provider

OLE DB Driver

ODBC Driver

SQL Server DataBase

DataSoure

Oracle DataBase

DataSoure

Hnh 7. 3: Cc lp gia code v ngun d liu. Mt trnh cung cp d liu l tp hp cc kiu c nh ngha trong namespace System.Data, cho bit cch giao tip vi mt ngun d liu c th. Mt trnh cung cp nh ngha mt tp hp cc kiu lp m cung cp cc chc nng c bn. Bng 7. 1: Cc i tng c bn ca mt trnh cung cp d liu ADO.NET. Object Base Class Implemented ngha Interfaces

Connection Command

DbConnection DbCommand

IDbConnection IDbCommand

Cung cp kh nng kt ni v ngt kt ni vi ngun d liu. Trnh by mt truy vn SQL hoc stored procedure. c ngun d liu theo mt chiu. Chuyn DataSets gia cc i tng gi (caller) v kho d liu. Miu t tn gi tham s bn trong truy vn c tham s (parameterized query).

DataReader DataAdapter Parameter

DbDataReader

ng gi (Encapsulates) mt database transaction. Mc d tn c th ca cc i tng c bn ny s khc nhau ty thuc trnh cung cp d liu (v d: SqlConnection khc vi OracleConnection khc vi OdbcConnection khc vi MySqlConnection), nhng mi i tng u k tha t mt lp c s (base class) (DbConnection trong trng hp cc i tng kt ni) v thi hnh interface (nh IDbConnection). Cc trnh cung cp d liu ADO.NET c cung cp bi Microsoft. Transaction Lu hnh ni b Trang 218

IDataReader, IDataRecord DbDataAdapter IDataAdapter, IDbDataAdapter DbParameter IDataParameter, IDbDataParamet er DbTransaction IDbTransaction

.NET ca Microsoft phn phi s lng ln cc trnh cung cp d liu, bao gm mt trnh cung cp cho Oracle, SQL Server, v kh nng lin kt OLE DB/ODBC. Bng 7.2 trnh by namespace v assembly cho mi trnh cung cp d liu ca Microsoft Bng 7. 2: Cc trnh cung cp d liu ADO.NET ca Microsoft Data Provider Namespace Assembly System.Data.dll OLE DB System.Data.OleDb System.Data.dll Microsoft SQL Server System.Data.SqlClient Microsoft SQL Server System.Data.SqlServerCe System.Data.SqlServerCe.dll Mobile System.Data.dll ODBC System.Data.Odbc Oracle System.Data.OracleClient System.Data.OracleClient.dll Trnh cung cp d liu OLE DB v ODBC ch hu ch nu tng tc vi mt DBMS m khng nh ngha mt trnh cung cp d liu .NET c th. 7.3 Cc namespace ca ADO.NET .NET cung cp mt s namespace cho ADO.NET, mt vi namespace trong c th hin trong bng 7.3. Bng 7. 3: Cc namespace ca ADO.NET Namespace ngha Microsoft.SqlServer.Server Namespace ny cung cp cc loi phc v vic tch hp CLR v SQL Server 2005 c d dng. Namespace ny nh ngha cc loi ADO.NET c s c s System.Data dng bi tt c trnh cung cp d liu, bao gm cc Interface ph bin v cc loi th hin lp ngt kt ni. (DataSet, DataTable, etc.). Namespace ny cha cc loi c dng chung trong tt c cc System.Data.Common trnh cung cp ca ADO.NET, bao gm cc lp c s o (abstract base classe) ph bin. Namespace ny cha cc loi m cho php nhn ra cc th hin System.Data.Sql Microsoft SQL Server c ci t trn mng cc b hin hnh. Namespace ny cha cc loi d liu t nhin (native data System.Data.SqlTypes types) c dng bi Microsoft SQL Server. Namespace System.Data Namespace ny cha cc loi c dng chung trong tt c cc trnh cung cp d liu ca ADO.NET. Bng 7-4 lit k mt vi loi chnh. Bng 7. 4: Cc thnh vin chnh ca System.Data Namespace Type ngha Constraint DataColumn Lu hnh ni b Trnh by (Represent) mt rng buc cho mt i tng DataColumn cho. Trnh by mt column bn trong mt i tng DataTable. Trang 219

DataRelation DataRow DataSet DataTable DataTableReader DataView IDataAdapter IDataParameter IDataReader IDbCommand IDbDataAdapter IDbTransaction

Trnh by mi quan h parent/child gia hai i tng DataTable. Trnh by mt dng bn trong mt i tng DataTable. Trnh by mt vng trong b nh ca d liu bao gm mi thnh phn ca i tng DataTable c quan h vi nhau. Trnh by bng trong b nh Cho php xem xt mt DataTable. Trnh by mt view ca mt DataTable cho vic sp xp, vic lc, vic tm kim, chnh sa v iu hng. nh ngha cch hnh x chnh (core behavior) ca mt i tng DataAdapter. nh ngha cch hnh x chnh (core behavior) ca mt i tng parameter. nh ngha cch hnh x chnh (core behavior) ca mt i tng DataReader. nh ngha cch hnh x chnh (core behavior) ca mt i tng command. K tha IDataAdapter cung cp thm cc chc nng ca mt i tng DataAdapter nh ngha cch hnh x ct li (core behavior) ca mt i tng Transaction.

Vai tr ca IDbConnection Interface c thi hnh bi i tng connection ca trnh cung cp d liu. Interface ny nh ngha mt tp hp cc thnh phn c dng to mt kt ni n kho d liu, v n cng cho php ly c i tng Transaction ca trnh cung cp d liu. Di y nh ngha ca IDbConnection: public interface IDbConnection : IDisposable { string ConnectionString { get; set; } int ConnectionTimeout { get; } string Database { get; } ConnectionState State { get; } IDbTransaction BeginTransaction(); IDbTransaction BeginTransaction(IsolationLevel il); void ChangeDatabase(string databaseName); void Close(); IDbCommand CreateCommand(); void Open(); } Ch : phng thc Close() l tng ng v mt chc nng vi vic gi phng thc Dispose() trc tip hoc gin tip bn trong phm vi using ca C#. Vai tr ca IDbTransaction Interface. Vic np chng phng thc BeginTransaction() (overloaded BeginTransaction() method) c nh ngha bi IDbConnection cung cp truy xut n i tng Transaction ca trnh

Lu hnh ni b

Trang 220

cung cp. Vic s dng cc thnh phn c nh ngha bi IDbTransaction, chng ta c th tng tc vi mt phin chuyn giao (transactionnal session) v kho d liu di. public interface IDbTransaction : IDisposable { IDbConnection Connection { get; } IsolationLevel IsolationLevel { get; } void Commit(); void Rollback(); } Vai tr ca IDbCommand Interface. IDbCommand Interface c thi hnh bi i tng command ca trnh cung cp d liu. i tng command cho php thao tc vi cc cu lnh SQL, Stored Procedures, v cc truy vn c tham s (parameterized queries). Trong phn b sung, cc i tng command truy xut n DataReder ca trnh cung cp d liu thng qua vic np chng phng thc ExecuteReader() (overloaded ExecuteReader() method). public interface IDbCommand : IDisposable { string CommandText { get; set; } int CommandTimeout { get; set; } CommandType CommandType { get; set; } IDbConnection Connection { get; set; } IDataParameterCollection Parameters { get; } IDbTransaction Transaction { get; set; } UpdateRowSource UpdatedRowSource { get; set; } void Cancel(); IDbDataParameter CreateParameter(); int ExecuteNonQuery(); IDataReader ExecuteReader(); IDataReader ExecuteReader(CommandBehavior behavior); object ExecuteScalar(); void Prepare(); } Vai tr ca Interface IDbDataParameter v IDataParameter. Interface ny cung cp truy xut n mt tp hp cc loi lp ty (compliant) IDbDataParameter (v d: cc i tng tham s): public interface IDbDataParameter : IDataParameter { byte Precision { get; set; } byte Scale { get; set; } int Size { get; set; } } IDbDataParameter k tha (extend) interface IDataParameter c c cc hnh x (behaveors) b sung sau y: public interface IDataParameter { DbType DbType { get; set; } Lu hnh ni b Trang 221

ParameterDirection Direction { get; set; } bool IsNullable { get; } string ParameterName { get; set; } string SourceColumn { get; set; } DataRowVersion SourceVersion { get; set; } object Value { get; set; } } Chc nng ca cc Interface IDbDataParameter v IDataParameter cho php trnh by cc tham s bn trong mt lnh SQL (bao gm Stored Procedures) qua cc i tng parameter ca ADO.NET c th hn l nhng k t chui hard-coded. Vai tr ca IDbDataAdapter and IDataAdapter Interfaces. IDbDataAdapter Interface nh ngha mt tp hp cc thuc tnh m c dng duy tr cc cu lnh SQL cho cc hot ng c lin quan n select, insert, update v delete. public interface IDbDataAdapter : IDataAdapter { IDbCommand DeleteCommand { get; set; } IDbCommand InsertCommand { get; set; } IDbCommand SelectCommand { get; set; } IDbCommand UpdateCommand { get; set; } } C 4 thuc tnh c thm vo, DataAdapter cng c nh ngha trong Interface c s, IDataAdapter. Interface ny nh ngha chc nng chnh ca mt loi DataAdapter: kh nng chuyn cc DataSet gia i tng gi v kho d liu bn di s dng cc phng thc Fill() v Update(). IDataAdapter Interface cho php nh x cc tn ct trong bng d liu thnh cc tn hin th thn thin vi ngi dng hn thng qua thuc tnh TableMappings. public interface IDataAdapter { MissingMappingAction MissingMappingAction { get; set; } MissingSchemaAction MissingSchemaAction { get; set; } ITableMappingCollection TableMappings { get; } int Fill(System.Data.DataSet dataSet); DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType); IDataParameter[] GetFillParameters(); int Update(DataSet dataSet); } Vai tr ca IDataReader and IDataRecord. Interface IDataReader trnh by cc hnh s (behaviors) ph bin c h tr bi mt i tng DataReader cho trc. public interface IDataReader : IDisposable, IDataRecord { int Depth { get; } bool IsClosed { get; } int RecordsAffected { get; } void Close(); DataTable GetSchemaTable(); bool NextResult(); Lu hnh ni b Trang 222

bool Read(); } IDataReader k tha IDataRecord, nh ngha mt s thnh phn cho php trch mt gi tr c phn loi mt cch r rng. Di y l danh sch khng y ca cc phng thc GetXXX() khc nhau c nh ngha bi IDataRecord. public interface IDataRecord { int FieldCount { get; } object this[ string name ] { get; } object this[ int i ] { get; } bool GetBoolean(int i); byte GetByte(int i); char GetChar(int i); DateTime GetDateTime(int i); Decimal GetDecimal(int i); float GetFloat(int i); short GetInt16(int i); int GetInt32(int i); long GetInt64(int i); ... bool IsDBNull(int i); } Ch : phng thc IDataReader.IsDBNull()thit lp gi tr cho mt trng l null. 7.5. Tm hiu c ch kt ni ca ADO.NET qua Connected Layer kt ni vi CSDL v c cc mu tin s dng i tng DataReader, thc hin cc bc sau: B1. Ch nh, cu hnh v m i tng kt ni. B2. Ch nh v cu hnh i tng Command, ch r i tng Connection nh mt Constructor c i s hoc qua thuc tnh Connection. B3. Gi ExecuteReader() trn i tng Command c cu hnh. B4. X l mi mu tin s dng phng thc Read() ca DataReader.

Hnh 7.4: Kt ni n CSDL v c cc mu tin theo hai cch. Lu hnh ni b Trang 223

Lm vic vi cc i tng Connection. Cc dng khai bo chui kt ni tu theo loi Database Provider Cc khai bo Connection String : [OleDB Provider] OleDbConnection myConnection = new OleDbConnection(); // Windows Authentication myConnection.ConnectionString = "Provider=SQLOLEDB.1;Data Source=localhost;" +"Initial Catalog=Pubs;Integrated Security=SSPI"; // SQL Authentication myConnection.ConnectionString = "Provider=SQLOLEDB.1;Data Source=localhost;" + "Initial Catalog=Pubs;User ID=sa;Password=123456"; [SQLServer Provider] SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = "Data Source=localhost;" + "Initial Catalog=Pubs;Integrated Security=SSPI"; [AttachDBFile] vi tp tin CSDL myConnection.ConnectionString = @"Data Source=localhost\SQLEXPRESS;" + @"AttachDBFilename=|DataDirectory|\Pubs.mdf;Integrated Security=True"; Bc th nht khi lm vic vi mt trnh cung cp d liu l thit lp mt session vi ngun d liu s dng i tng connection (k tha t DbConnection). Cc i tng Connection ca .NET c cung cp vi mt chui kt ni c nh dng, gm mt s cp name/value c phn cch bi du chm phy (;). Thng tin ny c dng ch nh tn my s kt ni, cc thit lp bo mt c yu cu, tn ca CSDL trn my , v thng tin trnh cung cp d liu c th khc. Tn Initial Catalog xc nh tn CSDL. Data Source xc nh tn my cha CSDL. y, (local) cho php chng ta nh ngha mt Token ring bit (single) ch r my cc b hin hnh, khi token \SQLEXPRESS cho trnh cung cp d liu SQL bit chng ta ang kt ni n bn ci t SQL Server Express edition (nu chng ta c Pubs trn SQL Server 2005/2008 hoc cc phin bn trc y, ch r Data Source=(local)\SQLEXPRESS). Integrated Security thit lp thng tin bo mt, nu chn Integrated Security l SSPI (tng ng true), s dng ti khon Windows hin hnh xc nhn quyn ngi dng. User ID + Password thit lp thng tin bo mt, nu chn s dng ti khon SQL Server hin hnh xc nhn quyn ngi dng. Sau khi chui kt ni c thit lp, gi Open() m kt ni vi CSDL. Ngoi vic b sung cc thnh phn ConnectionString, Open(), v Close(), mt i tng kt ni cung cp mt s thnh phn m cho php thm vo cc thit lp thuc v cu hnh kt ni, nh l cc thit lp Timeout, thng tin thuc v giao tc (transactional). Bng 7.5 lit k mt vi cc thnh phn ca lp c s DbConnection. Bng 7.5: Cc thnh phn ca DbConnection Member ngha BeginTransaction() Phng thc ny c s dng bt u mt database Transaction. Phng thc ny thay i CSDL trn mt kt ni m (open ChangeDatabase() connection) ConnectionTimeout Thuc tnh ny tr ra mt khong thi gian ch trong khi thit lp mt Lu hnh ni b Trang 224

Database DataSource GetSchema() State

kt ni trc khi kt thc v to ra mt li (mc nh l 15 giy). Thuc tnh ny ly ra tn ca CSDL c duy tr bi i tng connection. Thuc tnh ny ly v tr ca CSDL c duy tr bi i tng connection. Phng thc ny tr ra mt DataSet m cha thng tin bng t ngun d liu. Thuc tnh ny thit lp trng thi hin hnh ca vic kt ni, c th hin bi vic lit k ConnectionState.

Th d 1: To trang ConnectionTester.aspx thc hin vic to kt ni n CSDL MS SQL Server s dng i tng SqlConnection vi chui kt ni c dng sau:
// Thit lp chui kt ni n database Pubs. string connectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=Pubs;"; if (optWindows.Checked) { // xc thc vi Windows Authenticate connectionString += "Integrated Security=SSPI"; } else { // xc thc vi SQL Authenticate connectionString += "User ID=sa;Password=123456"; } // Define the ADO.NET Connection object. SqlConnection myConnection = new SqlConnection(connectionString); Ni dung thit k trang ConnectionTester.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ConnectionTester.aspx.cs" Inherits="ConnectionTester" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:RadioButton id="optSQL" runat="server" Text="Use SQL Authentication (with sa account)" GroupName="Authentication" Font-Size="Smaller" FontNames="Verdana"></asp:RadioButton> <br /> <asp:RadioButton id="optWindows" runat="server" Text="Use Windows Integrated Authentication" GroupName="Authentication" Font-Size="Smaller" FontNames="Verdana" Checked="True"></asp:RadioButton> <br /> <br />

Lu hnh ni b

Trang 225

<asp:button id="cmdConnect" runat="server" Text="Connect" onclick="cmdConnect_Click"></asp:button> <br /> <br /> <asp:label id="lblInfo" runat="server" Height="128px" Width="464px" FontSize="Small" Font-Names="Verdana" ForeColor="Maroon"></asp:label> </div> </form> </body> </html> Phn m lnh ConnectionTester.aspx.cs public partial class ConnectionTester : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void cmdConnect_Click(object sender, EventArgs e) { // Define the connection string. string connectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=Pubs;"; if (optWindows.Checked) { connectionString += "Integrated Security=SSPI"; } else { connectionString += "User ID=sa;Password=123456"; } // Define the ADO.NET Connection object. SqlConnection myConnection = new SqlConnection(connectionString); try { // Try to open the connection. myConnection.Open(); lblInfo.Text = "<b>Server Version:</b> " + myConnection.ServerVersion; lblInfo.Text += "<br /><b>Connection Is:</b> " + myConnection.State.ToString(); } catch (Exception err) { // Handle an error by displaying the information. lblInfo.Text = "Error reading the database. "; lblInfo.Text += err.Message; } finally { // Either way, make sure the connection is properly closed. // (Even if the connection wasn't opened successfully, // calling Close() won't cause an error.) myConnection.Close();

Lu hnh ni b

Trang 226

lblInfo.Text += "<br /><b>Now Connection Is:</b> "; lblInfo.Text += myConnection.State.ToString(); } } }

Kt qu thc thi trong hai trng hp kt ni CSDL b li hay thnh cng.

Lm vic vi cc i tng ConnectionStringBuilder Lm vic vi cc chui kt ni c th hi cng knh, chng c trnh by nh cc k t chui, m tht kh khn bo tr v d xy ra li. Cc trnh cung cp d liu ADO.NET c Microsoft h tr cc i tng trnh to chui kt ni (connection string builder) , cho php thit lp cc cp name/value s dng cc thuc tnh c nh kiu r rng. y, to mt th hin ca SqlConnectionStringBuilder, thit lp cc thuc tnh ph hp, v ly c chui trong thng qua thuc tnh ConnectionString. Mt khi kt hp i tng vi d liu chui ban u, chng ta c th thay i cp gi tr name/value s dng cc thuc tnh c lin quan. Th d 2: Thm vo mt on m lnh s dng i tng SqlConnectionStringBuilder ly ni dung trong chui connectionString v thit lp gi tr name/value tng ng cho cc thuc tnh DataSource, UserID, Password,
protected void cmdConnect_Click(object sender, EventArgs e) { // Define the connection string. string connectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=Pubs;"; if (optWindows.Checked) { connectionString += "Integrated Security=SSPI"; } else { connectionString += "User ID=sa;Password=123456"; } // Define the ADO.NET Connection object. SqlConnection myConnection = new SqlConnection(connectionString); try { // Try to open the connection. myConnection.Open(); lblInfo.Text = "<b>Server Version:</b> " + myConnection.ServerVersion; lblInfo.Text += "<br /><b>Connection Is:</b> " + myConnection.State.ToString(); // Create a new SqlConnectionStringBuilder based on the // partial connection string retrieved from the config file.

Lu hnh ni b

Trang 227

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString); SqlConnectionStringBuilder builder2 = new SqlConnectionStringBuilder(); // Supply the additional values. builder2.DataSource = builder.DataSource; builder2.UserID = builder.UserID; builder2.Password = builder.Password; lblInfo.Text += "<br /><b>ConnectionString Is:</b> " + builder2.ConnectionString; } catch (Exception err) { // Handle an error by displaying the information. lblInfo.Text = "Error reading the database. "; lblInfo.Text += err.Message; } finally { // Either way, make sure the connection is properly closed. // (Even if the connection wasn't opened successfully, // calling Close() won't cause an error.) myConnection.Close(); lblInfo.Text += "<br /><b>Now Connection Is:</b> "; lblInfo.Text += myConnection.State.ToString(); } }

Kt qu thc thi trang ConnectionTester.aspx

Mt cch khc, thc hin vic khai bo cu hnh ConnectionString trong Web.config : khng cn phi hard-code cc trang m lnh
<configuration> <connectionStrings> <add name="Northwind" connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI"/> </connectionStrings> .. </configuration>

Ly ni dung ConnectionString trong th <connectionStrings> trong tp tin Web.config. Ch phi khai bo thm :
using System.Web.Configuration;

Lu hnh ni b

Trang 228

private string connectionString = WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;

Lm vic vi cc i tng Command. Sau khi kt ni vi CSDL, vic tip theo l submit cc truy vn SQL n CSDL. Kiu SqlCommand (k tha t DbCommand). Kiu ca Command theo l thuyt s dng thuc tnh CommandType, m c th ly ra bt c gi tr no t CommandType enum: public enum CommandType { StoredProcedure, TableDirect, Text // Default value. } Khi to mt i tng command, cng c th kt hp truy vn SQL nh mt Constructor c tham s hoc trc tip thng qua thuc tnh CommandText. Ngoi ra khi ang to mt i tng command, cn ch r kt ni c s dng. Mt khc, c th to mt Constructor c i s hoc thng qua thuc tnh Connection: SqlConnection cn = new SqlConnection(); ... // Create command object via ctor args. string strSQL = "Select * From Customers"; SqlCommand myCommand = new SqlCommand(strSQL, cn); // Create another command object via properties. SqlCommand testCommand = new SqlCommand(); testCommand.Connection = cn; testCommand.CommandText = strSQL; ... Bng 7. 6: Cc thnh phn ca DbCommand Member ngha Ly ra hoc thit lp thi gian ch trong khi ang thc thi lnh trc CommandTimeout khi kt thc. Ly ra hoc thit lp DbConnection c dng bi th hin ny ca Connection DbCommand. Ly ra tp hp cc kiu ca DbParameter c dng cho mt truy vn Parameters c tham s. Hy b vic thc thi ca mt lnh. Cancel() Thc hin cu lnh trong CommandText. Kt qu tr v l taReader ExecuteReader() ca trnh cung cp d liu. ExecuteNonQuery() Thc hin cu lnh trong CommandText v khng c kt qu tr v. Thc hin cu lnh trong CommandText, kt qu tr v l mt gi tr ExecuteScalar() n. ExecuteXmlReader() Phng thc ny tr ra mt System.Xml.XmlReader m cho php x l lung u vo ca XML Lu hnh ni b Trang 229

Prepare()

To mt phin bn c chun b (hoc c bin dch) ca lnh trn ngun d liu.

Lm vic vi cc Data Reader Mt khi thit lp mt kt ni thc s v cu lnh SQL, bc tip theo l submit truy vn n ngun d liu. Kiu DbDataReader (m thc thi giao din IDataReader) l cch n gin v chc chn ly ra thng tin t mt kho d liu. Cc i tng DataReader thu c t i tng Command qua li gi n ExecuteReader(). Khi lm vic vi phng thc ny, c th ng mt cch t ng i tng kt ni c lin quan bi vic ch r CommandBehavior.CloseConnection. Vic s dng phng thc Read() ca DataReader duyt qua cc mu tin, (tr ra gi tr false nu duyt qua mu tin cui cng). Ch rng chng ta gi Close() ngay khi kt thc vic x l cc mu tin, gii phng i tng kt ni: Indexer ca mt i tng DataReader c overload ly mt chui (string) (miu t tn ca ct) hoc mt int (miu t s th t ca ct). Do , c th trnh cc tn chui hard-code vi vic cp nht di y (ch s dng thuc tnh FieldCount) Th d 3: To trang AuthorBrowser.aspx thc hin c ni dung ca bng Authors trong CSDL Pubs v a vo mt DropdownList. Khi chn mt gi tr trong DropdownList, ni dung mu tin la chn s c hin th trn trang. Ni dung thit k trang AuthorBrowser.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AuthorBrowser.aspx.cs" Inherits="AuthorBrowser" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:label id="Label1" runat="server" Width="120px" Height="20px">Select Author:</asp:label>&nbsp; <asp:dropdownlist id="lstAuthor" runat="server" Width="256px" Height="22px" AutoPostBack="True" onselectedindexchanged="lstAuthor_SelectedIndexChanged"> </asp:dropdownlist> <br /> <br /> <br /> <asp:label id="lblResults" runat="server" Width="384px" Height="168px"> </asp:label> </div> </form> </body> </html> Phn m lnh trang AuthorBrowser.aspx.cs public partial class AuthorBrowser : System.Web.UI.Page {

Lu hnh ni b

Trang 230

private string connectionString = WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { FillAuthorList(); } } private void FillAuthorList() { lstAuthor.Items.Clear(); // Define the Select statement. // Three pieces of information are needed: the unique id, // and the first and last name. string selectSQL = "SELECT au_lname, au_fname, au_id FROM Authors"; // Define the ADO.NET objects. SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(selectSQL, con); SqlDataReader reader; // Try to open database and read information. try { con.Open(); reader = cmd.ExecuteReader(); // For each item, add the author name to the displayed // list box text, and store the unique ID in the Value Thuc tnh. while (reader.Read()) { ListItem newItem = new ListItem(); newItem.Text = reader["au_lname"] + ", " + reader["au_fname"]; newItem.Value = reader["au_id"].ToString(); lstAuthor.Items.Add(newItem); } reader.Close(); } catch (Exception err) { lblResults.Text = "Error reading list of names. "; lblResults.Text += err.Message; } finally { con.Close(); } } protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e) {

Lu hnh ni b

Trang 231

// Create a Select statement that searches for a record // matching the specific author id from the Value Thuc tnh. string selectSQL; selectSQL = "SELECT * FROM Authors "; selectSQL += "WHERE au_id='" + lstAuthor.SelectedItem.Value + "'"; // Define the ADO.NET objects. SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(selectSQL, con); SqlDataReader reader; // Try to open database and read information. try { con.Open(); reader = cmd.ExecuteReader(); reader.Read(); StringBuilder sb = new StringBuilder(); sb.Append("<b>"); sb.Append(reader["au_lname"]); sb.Append(", "); sb.Append(reader["au_fname"]); sb.Append("</b><br />"); sb.Append("Phone: "); sb.Append(reader["phone"]); sb.Append("<br />"); sb.Append("Address: "); sb.Append(reader["address"]); sb.Append("<br />"); sb.Append("City: "); sb.Append(reader["city"]); sb.Append("<br />"); sb.Append("State: "); sb.Append(reader["state"]); sb.Append("<br />"); lblResults.Text = sb.ToString(); reader.Close(); } catch (Exception err) { lblResults.Text = "Error getting author. "; lblResults.Text += err.Message; } finally { con.Close(); } } }

Kt qu thc hin:

Lu hnh ni b

Trang 232

Kt qu thc thi sau khi la chn gi tr trong DropdownList, thc thi s kin SelectedIndexChanged cho ra thng tin gi tr chn :

Thu c nhiu b kt qu s dng DataReader. Cc i tng DataReader c th thu c nhiu b kt qu s dng mt i tng Command. Th d, thu c tt c cc dng t bng Inventory cng nh t bng Customers, chng ta c th ch nh cc cu lnh SQL select s dng du chm phy (;) cui dng: string strSQL = "Select * From Inventory; Select * from Customers"; Mt khi chng ta thu c DataReader, chng ta c th duyt qua cc mu tin thng qua phng thc NextResult().
do{ while (myDataReader.Read()) { for (int i = 0; i < myDataReader.FieldCount; i++) { . myDataReader.GetName(i); myDataReader.GetValue(i).ToString().Trim(); } .. } } while (myDataReader.NextResult());

Lu hnh ni b

Trang 233

Lm vic vi cc i tng Parameterized Command Mt parameterized query c dng trnh by cc tham s SQL nh cc i tng. Cc truy vn c tham s thc thi nhanh hn mt chui SQL bnh thng, bi v chng c phn tch mt cch r rng (hn l chui SQL c gn n thuc tnh CommandText). h tr cc truy vn c tham s, i tng Command ca ADO.NET duy tr mt tp hp ca cc i tng tham s ring bit. Mc nh, tp hp ny empty, nhng chng ta d dng thm bt c gi tr no ca i tng tham s m nh x n mt tham s thay th trong truy vn SQL. Khi mun kt hp mt tham s bn trong mt truy vn SQL n mt thnh vin trong tp hp cc tham s ca i tng command, thm tin t @ trc tham s SQL. Ch r cc tham s s dng DbParameter. xy dng mt truy vn c tham s, chng ra bt u vi DbParameter (l lp c s cho i tng tham s c th ca mt trnh cung cp). Lp ny cha mt s thuc tnh m cho php chng ta cu hnh tn, kch c v kiu d liu ca tham s, cng nh cc c im khc nh l hng ca tham s. Bng 1. 7: Cc thnh phn chnh ca DbParameter Thuc tnh ngha Ly ra hoc thit lp kiu d liu t nhin t ngun d liu, c trnh DbType by nh kiu d liu CLR. Ly ra hoc thit lp tham s ch nhp, ch xut, c hai, hoc tr ra tham s gi tr. Ly ra hoc thit lp tham s chp nhn cc ga tr Null. IsNullable ParameterName Ly ra hoc thit lp tn ca DbParameter. Ly ra hoc thit lp kch c tham s ti thiu ca d liu (ch tht s hu Size ch cho d liu l vn bn). Direction Ly ra hoc thit lp gi tr cho tham s. Value minh ha tp hp ca cc i tng command ca cc i tng DBParameter quan st on code sau :
// Define ADO.NET objects. string insertSQL; insertSQL = "INSERT INTO Authors ("; insertSQL += "au_id, au_fname, au_lname, "; insertSQL += "phone, address, city, state, zip, contract) "; insertSQL += "VALUES ("; insertSQL += "@au_id, @au_fname, @au_lname, "; insertSQL += "@phone, @address, @city, @state, @zip, @contract)"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(insertSQL, con);

Sau a cc Parameters vi cc gi tr ly t cc iu khin nhp vo trong i tng Command hin ti cmd


// Add the parameters. cmd.Parameters.AddWithValue("@au_id", txtID.Text); cmd.Parameters.AddWithValue("@au_fname", txtFirstName.Text); cmd.Parameters.AddWithValue("@au_Lname", txtLastName.Text); cmd.Parameters.AddWithValue("@phone", txtPhone.Text); cmd.Parameters.AddWithValue("@address", txtAddress.Text);

Lu hnh ni b

Trang 234

cmd.Parameters.AddWithValue("@city", txtCity.Text); cmd.Parameters.AddWithValue("@state", txtState.Text); cmd.Parameters.AddWithValue("@zip", txtZip.Text); cmd.Parameters.AddWithValue("@contract", Convert.ToInt16(chkContract.Checked));

Hoc khi to i tng SqlParameter v t vo trong phn danh sch tham s ca i tng Command.
// Add the parameters. cmd.Parameters.Add(new SqlParameter("@au_id", txtID.Text)); cmd.Parameters.Add(new SqlParameter("@au_fname", txtFirstName.Text)); cmd.Parameters.Add(new SqlParameter("@au_Lname", txtLastName.Text)); cmd.Parameters.Add(new SqlParameter("@phone", txtPhone.Text)); cmd.Parameters.Add(new SqlParameter("@address", txtAddress.Text)); cmd.Parameters.Add(new SqlParameter("@city", txtCity.Text)); cmd.Parameters.Add(new SqlParameter("@state", txtState.Text)); cmd.Parameters.Add(new SqlParameter("@zip", txtZip.Text)); cmd.Parameters.Add(new SqlParameter("@contract", Convert.ToInt16(chkContract.Checked)));

Th d 4: To trang AuthorManager.aspx thit v vi giao din sau :


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AuthorManager.aspx.cs" Inherits="AuthorManager" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <div style="background-color: #FFE0C0; height: 70px; width: 601px; padding: 7px"> <br /> <asp:Label id="Label1" runat="server" Width="99px" Height="19px">Select Author:</asp:Label> <asp:DropDownList id="lstAuthor" runat="server" Width="187px" Height="21px" AutoPostBack="True" onselectedindexchanged="lstAuthor_SelectedIndexChanged"></asp:DropDownList>&nbsp;& nbsp;&nbsp; <asp:Button id="cmdUpdate" runat="server" Text="Update" onclick="cmdUpdate_Click"></asp:Button>&nbsp; <asp:Button id="cmdDelete" runat="server" Text="Delete" onclick="cmdDelete_Click"></asp:Button> <br /> <asp:Label id="Label11" runat="server" Width="99px" Height="19px">Or:</asp:Label> <asp:Button id="cmdNew" runat="server" Width="91px" Height="24px" Text="Create New" onclick="cmdNew_Click"></asp:Button>&nbsp; <asp:Button id="cmdInsert" runat="server" Width="85px" Height="24px" Text="Insert New" onclick="cmdInsert_Click"></asp:Button> </div> <br />

Lu hnh ni b

Trang 235

<div style="background-color: #E0E0E0; height: 392px; width: 601px; padding: 7px"> <asp:Label id="Label7" runat="server" Width="70px">Unique ID:</asp:Label> <asp:TextBox id="txtID" runat="server" Width="184px"></asp:TextBox>&nbsp; (required:&nbsp;###-##-#### form)<br /> <asp:Label id="Label2" runat="server" Width="70px">First Name:</asp:Label> <asp:TextBox id="txtFirstName" runat="server" Width="184px"></asp:TextBox><br /> <asp:Label id="Label3" runat="server" Width="70px">Last Name:</asp:Label> <asp:TextBox id="txtLastName" runat="server" Width="183px"></asp:TextBox><br /> <asp:Label id="Label4" runat="server" Width="70px">Phone:</asp:Label> <asp:TextBox id="txtPhone" runat="server" Width="183px"></asp:TextBox><br /> <asp:Label id="Label5" runat="server" Width="70px">Address:</asp:Label> <asp:TextBox id="txtAddress" runat="server" Width="183px"></asp:TextBox><br /> <asp:Label id="Label6" runat="server" Width="70px">City:</asp:Label> <asp:TextBox id="txtCity" runat="server" Width="184px"></asp:TextBox><br /> <asp:Label id="Label7" runat="server" Width="70px">State:</asp:Label> <asp:TextBox id="txtState" runat="server" Width="184px"></asp:TextBox><br /> <asp:Label id="Label9" runat="server" Width="70px">Zip Code:</asp:Label> <asp:TextBox id="txtZip" runat="server" Width="184px"></asp:TextBox>&nbsp; (required: any five&nbsp;digits)<br /> <br /> <asp:Label id="Label8" runat="server" Width="93px" Height="19px">Contract:</asp:Label>&nbsp; <asp:CheckBox id="chkContract" runat="server"></asp:CheckBox><br /> <br /> <asp:Label id="lblResults" runat="server" Width="575px" Height="121px" FontBold="True"></asp:Label> </div> </div> </form> </body> </html> Giao din trang AuthorManager.aspx nh hnh sau:

Lu hnh ni b

Trang 236

Phn m lnh thc thi trn trang AuthorManager.aspx.cs


public partial class AuthorManager : System.Web.UI.Page { private string connectionString = WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { FillAuthorList(); } } private void FillAuthorList() { lstAuthor.Items.Clear(); // Define the Select statement. // Three pieces of information are needed: the unique id, // and the first and last name. string selectSQL = "SELECT au_lname, au_fname, au_id FROM Authors"; // Define the ADO.NET objects. SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(selectSQL, con); SqlDataReader reader; // Try to open database and read information. try { con.Open(); reader = cmd.ExecuteReader();

Lu hnh ni b

Trang 237

// For each item, add the author name to the displayed // list box text, and store the unique ID in the Value Thuc tnh. while (reader.Read()) { ListItem newItem = new ListItem(); newItem.Text = reader["au_lname"] + ", " + reader["au_fname"]; newItem.Value = reader["au_id"].ToString(); lstAuthor.Items.Add(newItem); } reader.Close(); } catch (Exception err) { lblResults.Text = "Error reading list of names. "; lblResults.Text += err.Message; } finally { con.Close(); } } protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e) { // Define ADO.NET objects. string selectSQL; selectSQL = "SELECT * FROM Authors "; selectSQL += "WHERE au_id='" + lstAuthor.SelectedItem.Value + "'"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(selectSQL, con); SqlDataReader reader; // Try to open database and read information. try { con.Open(); reader = cmd.ExecuteReader(); reader.Read(); // Fill the controls. txtID.Text = reader["au_id"].ToString(); txtFirstName.Text = reader["au_fname"].ToString(); txtLastName.Text = reader["au_lname"].ToString(); txtPhone.Text = reader["phone"].ToString(); txtAddress.Text = reader["address"].ToString(); txtCity.Text = reader["city"].ToString(); txtState.Text = reader["state"].ToString(); txtZip.Text = reader["zip"].ToString(); chkContract.Checked = (bool)reader["contract"]; reader.Close(); lblResults.Text = ""; } catch (Exception err) { lblResults.Text = "Error getting author. ";

Lu hnh ni b

Trang 238

lblResults.Text += err.Message; } finally { con.Close(); } } protected void cmdNew_Click(object sender, EventArgs e) { txtID.Text = ""; txtFirstName.Text = ""; txtLastName.Text = ""; txtPhone.Text = ""; txtAddress.Text = ""; txtCity.Text = ""; txtState.Text = ""; txtZip.Text = ""; chkContract.Checked = false; lblResults.Text = "Click Insert New to add the completed record."; } protected void cmdInsert_Click(object sender, EventArgs e) { // Perform user-defined checks. if (txtID.Text == "" || txtFirstName.Text == "" || txtLastName.Text == "") { lblResults.Text = "Records require an ID, first name, and last name."; return; } // Define ADO.NET objects. string insertSQL; insertSQL = "INSERT INTO Authors ("; insertSQL += "au_id, au_fname, au_lname, "; insertSQL += "phone, address, city, state, zip, contract) "; insertSQL += "VALUES ("; insertSQL += "@au_id, @au_fname, @au_lname, "; insertSQL += "@phone, @address, @city, @state, @zip, @contract)"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(insertSQL, con); // Add the parameters. cmd.Parameters.Add(new SqlParameter("@au_id", txtID.Text)); cmd.Parameters.Add(new SqlParameter("@au_fname", txtFirstName.Text)); cmd.Parameters.Add(new SqlParameter("@au_Lname", txtLastName.Text)); cmd.Parameters.Add(new SqlParameter("@phone", txtPhone.Text)); cmd.Parameters.Add(new SqlParameter("@address", txtAddress.Text)); cmd.Parameters.Add(new SqlParameter("@city", txtCity.Text)); cmd.Parameters.Add(new SqlParameter("@state", txtState.Text)); cmd.Parameters.Add(new SqlParameter("@zip", txtZip.Text)); cmd.Parameters.Add(new SqlParameter("@contract", Convert.ToInt16(chkContract.Checked))); // Try to open the database and execute the update. int added = 0; try

Lu hnh ni b

Trang 239

{ con.Open(); added = cmd.ExecuteNonQuery(); lblResults.Text = added.ToString() + " record inserted."; } catch (Exception err) { lblResults.Text = "Error inserting record. "; lblResults.Text += err.Message; } finally { con.Close(); } // If the insert succeeded, refresh the author list. if (added > 0) { FillAuthorList(); } } protected void cmdUpdate_Click(object sender, EventArgs e) { // Define ADO.NET objects. string updateSQL; updateSQL = "UPDATE Authors SET "; updateSQL += "au_fname=@au_fname, au_lname=@au_lname, "; updateSQL += "phone=@phone, address=@address, city=@city, state=@state, "; updateSQL += "zip=@zip, contract=@contract "; updateSQL += "WHERE au_id=@au_id_original"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(updateSQL, con); // Add the parameters. cmd.Parameters.AddWithValue("@au_fname", txtFirstName.Text); cmd.Parameters.AddWithValue("@au_Lname", txtLastName.Text); cmd.Parameters.AddWithValue("@phone", txtPhone.Text); cmd.Parameters.AddWithValue("@address", txtAddress.Text); cmd.Parameters.AddWithValue("@city", txtCity.Text); cmd.Parameters.AddWithValue("@state", txtState.Text); cmd.Parameters.AddWithValue("@zip", txtZip.Text); cmd.Parameters.AddWithValue("@contract", Convert.ToInt16(chkContract.Checked)); cmd.Parameters.AddWithValue("@au_id_original", lstAuthor.SelectedItem.Value); // Try to open database and execute the update. int updated = 0; try { con.Open(); updated = cmd.ExecuteNonQuery(); lblResults.Text = updated.ToString() + " record updated."; } catch (Exception err)

Lu hnh ni b

Trang 240

{ lblResults.Text = "Error updating author. "; lblResults.Text += err.Message; } finally { con.Close(); } // If the updated succeeded, refresh the author list. if (updated > 0) { FillAuthorList(); } } protected void cmdDelete_Click(object sender, EventArgs e) { // Define ADO.NET objects. string deleteSQL; deleteSQL = "DELETE FROM Authors "; deleteSQL += "WHERE au_id=@au_id"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(deleteSQL, con); cmd.Parameters.AddWithValue("@au_id ", lstAuthor.SelectedItem.Value); // Try to open the database and delete the record. int deleted = 0; try { con.Open(); deleted = cmd.ExecuteNonQuery(); lblResults.Text = "Record deleted."; } catch (Exception err) { lblResults.Text = "Error deleting author. "; lblResults.Text += err.Message; } finally { con.Close(); } // If the delete succeeded, refresh the author list. if (deleted > 0) { FillAuthorList(); } } }

Lu hnh ni b

Trang 241

Kt qu thc thi:

Khi click chn mt tc gi, thng tin tc gi s in vo cc iu khin d liu nhp pha di:

Thc thi vic to mi mt mu tin tc gi, click nt [Create New] , h thng s t cc gi tr iu khin nhp d liu v ban u (rng) cho php vic nhp thng tin mi.
protected void cmdNew_Click(object sender, EventArgs e) { txtID.Text = ""; txtFirstName.Text = ""; txtLastName.Text = ""; txtPhone.Text = ""; txtAddress.Text = ""; txtCity.Text = ""; txtState.Text = ""; txtZip.Text = ""; chkContract.Checked = false; lblResults.Text = "Click Insert New to add the completed record."; } Sau khi nhp xong click nt [Insert New], triu gi phng thc cmdInsert_Click(object sender, EventArgs e)

Lu hnh ni b

Trang 242

protected void cmdInsert_Click(object sender, EventArgs e) { // Perform user-defined checks. if (txtID.Text == "" || txtFirstName.Text == "" || txtLastName.Text == "") { lblResults.Text = "Records require an ID, first name, and last name."; return; } // Define ADO.NET objects. string insertSQL; insertSQL = "INSERT INTO Authors ("; insertSQL += "au_id, au_fname, au_lname, "; insertSQL += "phone, address, city, state, zip, contract) "; insertSQL += "VALUES ("; insertSQL += "@au_id, @au_fname, @au_lname, "; insertSQL += "@phone, @address, @city, @state, @zip, @contract)"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(insertSQL, con); // Add the parameters. cmd.Parameters.Add(new SqlParameter("@au_id", txtID.Text)); cmd.Parameters.Add(new SqlParameter("@au_fname", txtFirstName.Text)); cmd.Parameters.Add(new SqlParameter("@au_Lname", txtLastName.Text)); cmd.Parameters.Add(new SqlParameter("@phone", txtPhone.Text)); cmd.Parameters.Add(new SqlParameter("@address", txtAddress.Text)); cmd.Parameters.Add(new SqlParameter("@city", txtCity.Text)); cmd.Parameters.Add(new SqlParameter("@state", txtState.Text)); cmd.Parameters.Add(new SqlParameter("@zip", txtZip.Text)); cmd.Parameters.Add(new SqlParameter("@contract", Convert.ToInt16(chkContract.Checked))); // Try to open the database and execute the update. int added = 0; try { con.Open(); added = cmd.ExecuteNonQuery(); lblResults.Text = added.ToString() + " record inserted."; } catch (Exception err) { lblResults.Text = "Error inserting record. "; lblResults.Text += err.Message; } finally { con.Close(); } // If the insert succeeded, refresh the author list. if (added > 0) { FillAuthorList(); } }

Sau khi sa i d liu ca mu tin tc gi hin ti trong cc khin nhp d liu, click nt [Update] cp nht li. Mun xo mu tin tc gi hin ti, click nt [Delete]. Lu hnh ni b Trang 243

Tm hiu cc DatabaseTransaction rng buc vic kim tra ca lp c kt ni ca ADO.NET, chng ta s tm khi nim ca mt Database Transaction. Mt cch n gin, Transaction (giao tc) l mt tp cc hnh ng cng thc hin mt chc nng, v chng ch c th cng nhau thnh cng, hoc cng nhau tht bi. Cc Transaction l rt quan trng khi mt thao tc CSDL cn phi tc ng vi nhiu bng hoc nhiu Stored Procedure (hoc phi hp ca cc phn nh ca CSDL). Th d: Ngn hng ca Soda mun tng li sut tin gi cho 700 khch hng. Do , Soda phi cp nht 700 record trong CSDL. Tuy nhin, trong khi server cp nht n record th 500 th b... cp in. Kt qu, ch c 500 khch hng c tng, 500 khch hng cn li ngi ch Soda... xin li. Ch n khi c in, Soda s c 2 la chn: mt l quay li, b vic cp nht cho 500 record u tin, hai l cp nht tip 500 record cn li. Vic cp nht 700 record nh trn c gi l mt Transaction (giao tc) Vic quay li, b cp nht 500 record u tin, c gi l qu trnh Rollback (quay li). Vic tip tc cp nht 500 record cn li, c gi l qu trnh Commit (tm dch l "cam kt"). Thng thng, ta s dng Transaction cho cc cu lnh SQL insert, update, delete trong CSDL. Nu ang thc hin m b mt in hay treo my, th khi h thng hot ng li, b qun l Transaction s t ng thc hin iu ny m khng cn ngi dng phi nhng tay vo. Chng ta c th lp trnh vi Transaction bn trong h qun tr CSDL (v d, vit bn trong StoreProcedure ca SQL Server). Hoc chng ta c th lp trnh ngay trong ng dng ca mnh, thng qua i tng Transaction ca ADO.NET. Cc thnh phn chnh ca mt i tng giao tc (Transaction) ca ADO.NET. Cc i tng Transaction c tm thy bn trong trnh cung cp d liu ADO.NET, tt c c k tha t DBTransaction v thc thi interface IDbTransaction. public interface IDbTransaction : IDisposable { IDbConnection Connection { get; } IsolationLevel IsolationLevel { get; } void Commit(); void Rollback(); } Ch : Thuc tnh Connection, m s tr ra mt tham chiu n i tng Connection m khi to Transaction hin hnh. Phng thc Commit() c gi khi mi thao tc trn CSDL thnh cng. Ngc li, phng thc Rollback() c th c gi khi mt bit l trong thi gian thc thi xut hin, v s thng bo DMBS b qua bt c s thay i no ang xem xt, li khng ng chm n d liu ban u. Ch : thuc tnh IsolationLevel ca mt i tng Transaction cho php chng ta ch r mt Transaction phi c xem xt chng li cc hnh ng ca cc Transaction song song khc. Mc nh, cc giao tc (transaction) c c lp mt cch hon ton cho n khi committed. Lu hnh ni b Trang 244

Ngoi cc thnh phn c nh ngha bi interface IDbTransaction, kiu SqlTransaction nh ngha mt thnh phn thm vo c t tn l Save(), m cho php nh ngha save points. Ni dung ny cho php rollback mt giao tc (transaction) b hng cho n mt im c t tn, thay v roll back ton b giao tc. Khi gi Save() s dng mt i tng SqlTransaction, chng ta c th ch r mt chui thn thin. Khi gi Rollback(), chng ta c th ch nh bit danh ny nh mt i s thc s. Khi gi Rollback() khng c i s, tt c cc s thay i ang xem xt c tr li t u. Th d v DatabaseTransaction minh ha vic s dng cc giao tc (transaction) ca ADO.NET, thm mt bng mi c tn CreditRisks n CSDL AutoLot, m c cc ct ging nh bng Customers (CustID [l primary key], FirstName, and LastName). Hnh ng di chuyn khch hang t Customers sang bng CreditRisks. Mt cch c th, chng ta cn chc chn rng chng ta xa mt cch thnh cng cc mu tin t bng Customers v thm chng n bng CreditRisks hoc khng c nhng thao tc no xy ra trn CSDL . minh ha cch lm vic vi giao tc (transaction) ca ADO.NET, quan st phng thc public vi tn ProcessCreditRisk() bn di:
// A new member of the InventoryDAL class. public void ProcessCreditRisk(bool throwEx, int custID) { // First, look up current name based on customer ID. string fName = string.Empty; string lName = string.Empty; SqlCommand cmdSelect = new SqlCommand( string.Format("Select * from Customers where CustID = {0}", custID), sqlCn); using (SqlDataReader dr = cmdSelect.ExecuteReader()) { while (dr.Read()) { fName = (string)dr["FirstName"]; lName = (string)dr["LastName"]; } } // Create command objects that represent each step of the operation. SqlCommand cmdRemove = new SqlCommand( string.Format("Delete from Customers where CustID = {0}", custID), sqlCn); SqlCommand cmdInsert = new SqlCommand(string.Format("Insert Into CreditRisks" + "(CustID, FirstName, LastName) Values" + "({0}, '{1}', '{2}')", custID, fName, lName), sqlCn); // We will get this from the connection object. SqlTransaction tx = null; try { tx = sqlCn.BeginTransaction(); // Enlist the commands into this transaction. cmdInsert.Transaction = tx; cmdRemove.Transaction = tx; // Execute the commands. cmdInsert.ExecuteNonQuery(); cmdRemove.ExecuteNonQuery(); // Simulate error.

Lu hnh ni b

Trang 245

if (throwEx) { throw new ApplicationException("Sorry! Database error! Tx failed..."); } // Commit it! tx.Commit(); } catch (Exception ex) { // Any error will roll back transaction. tx.Rollback(); } }

y, c mt tham s bool u vo th hin rng chng ta s nm ra mt bit l khi vic x l Customer b li. Mt khi chng ta thu c first v last name ca customer u tin da trn tham s custID, ch rng chng ta ang s dng hai i tng SqlCommand trnh by mi bc trong giao tc (transaction), v chng ta ly c mt i tng SqlTransaction hp l t i tng kt ni qua BeginTransaction(). Tip theo, quan trng nht, chng ta phi tranh th mi i tng command bi vic gn thuc tnh Transaction n i tng giao tc (transaction) m chng ta va ly ra. Sau khi gi ExecuteNonQuery() trn mi lnh, s nm ra mt bit l nu (v ch nu) gi tr ca tham s bool l ng. Trong trng hp ny, tt c cc thao tc CSDL sp xy ra s c roll back. Nu chng ta khng nm ra mt bit l, cc bc s b committed n cc bng CSDL mt khi chng ta gi Commit(). Tng kt. Trong phn ny, chng ta xem xt Connected Layer v tm hiu vai tr ca trnh cung cp d liu, vic thc thi c th ca mt vi lp c s o (trong System.Data.Common) truy xut n CSDL v cc kiu namespace and Interface (trong System.Data namespace). Xy dng c s m lnh s dng ADO.NET Data Provider Factory Model. Vic s dng cc i tng Connected, cc i tng giao tc (transaction), v cc i tng DataReader ca lp kt ni, select, update, insert, and delete cc mu tin. Cng nh vic gi cc i tng command h tr mt tp hp tham s bn trong, dng thc thi cc lnh SQL hoc Store Procedure 7.6. DISCONNECTED LAYER Khi s dng kha cnh ny ca ADO.NET, chng ta c th m hnh d liu ca CSDL bn trong tng gi s dng nhiu thnh phn ca namespace System.Data ( c bit l DataSet, DataTable, DataRow, DataColumn, DataView, v DataRelation). Khi s dng kha cnh "ngt kt ni " ny ca ADO.NET chng ta s thu c nhng i tng DataSet thng tr s dng i tng DataAdapter ca trnh cung cp d liu. Chc nng ca i tng DataAdapter nh mt cu ni gia tng client v mt CSDL quan h. 7.6.1. Tm hiu c ch ngt kt ni ca ADO.NET S dng nhng kiu ngt kt ni chng ta s tc ng n mt i tng c bit l Data Adapter load v update d liu. Nhng i tng DataAdapter s dng cc i tng DataSet chuyn d liu gia i tng gi v data source. Kiu DataSet l mt kho cha cc i tng DataTable, mi i tng cha mt tp hp cc i tng DataRow v DataColumn. Lu hnh ni b Trang 246

i tng DataAdapter ca trnh cung cp d liu x l vic kt ni CSDL mt cch t ng. Khi i tng gi nhn c i tng DataSet, tng gi b ngt kt ni hon ton t CSDL v ri khi vi mt bn sao cc b ca d liu. i tng gi c th insert, delete, hoc update nhng hng t mt DataTable cho, nhng CSDL vt l khng c cp nht cho n khi i tng gi chuyn DataSet ti DataAdapter cp nht.

Hnh 7.5: Cc i tng data adapter chuyn cc DataSet n tng client. 7.6.2. Tm hiu vai tr ca DataSet DataSet l mt th hin ca d liu quan h. Mt DataSet l mt lp cha ba colection bn trong (xem hnh 1.5)

Hnh 7.6: M hnh ca DataSet. Thuc tnh Tables ca DataSet cho php bn truy xut DataTableCollection m cha cc DataTable ring l. Mt DataSet c th c s dng th hin nhng mi quan h cha/con gia cc bng ca n. Chng hn, mt quan h c th c to ra gia hai bng m hnh mt s rng buc kha ngoi s dng kiu DataRelation. i tng ny c th sau c thm vo DataRelationCollection thng qua thuc tnh Relations. Thuc tnh ExtendedProperties cho php truy xut ti i tng Thuc tnhCollection m cho php bn kt hp bt k thng tin m rng no ti DataSet nh cp name/value. Chng hn, bn c th kt hp tn cng ty ca bn ti mt DataSet. Ch : Lp DataTable cng h tr nhng thuc tnh m rng qua thuc tnh ExtendedProperties. Cc thuc tnh chnh ca DataSet. Chng ta hy xem mt s thnh phn chnh ca DataSet. Bn ngoi nhng thuc tnh Tables, Relations, v ExtendedProperties. Bng 7.8 m t mt s thuc tnh b sung quan trng. Bng 7. 8: Cc thuc tnh quan trng ca DataSet Thuc tnh ngha Cho bit c phi nhng chui trong i tng DataTable l phn CaseSensitive bit hoa/thng hay khng. Th hin tn mt cch thn thin ca DataSet ny. DataSetName Lu hnh ni b Trang 247

EnforceConstraints HasErrors RemotingFormat

a ra hay thit lp mt gi tr cho bit c nhng quy tc rng buc hay khng. a ra mt gi tr cho bit c nhng li trong bt k hng no trong DataTables ca DataSet hay khng . Cho php bn nh ngha cch DataSet xut ni dung ca n ( nh phn hay XML).

Cc phng thc chnh ca DataSet. DataSet cung cp nhng phng thc m cho php bn sao chp ni dung DataSet ca bn, iu hng gia nhng bng bn trong, v thit lp nhng im bt u v kt thc ca mt l nhng s cp nht. Bng 1.9 m t mt s phng thc ct li. Bng 7.9: Cc phng thc quan trng ca DataSet Methods ngha Xc nhn mi s thay i gn nht n DataSet t khi n c AcceptChanges() load hay AcceptChanges(). Xa hon ton d liu DataSet bng vic loi b mi hng trong Clear() mi DataTable Sao chp cu trc ca DataSet, bao gm mi DataTables, cng Clone() nh tt c quan h v bt k s rng buc no. Sao chp c cu trc ln d liu cho DataSet. Copy() Tr v mt s sao chp ca DataSet cha mi s thay i c to GetChanges() ra n khi n c load gn nht hay t khi AcceptChanges() c gi. a ra mt gi tr cho bit c phi DataSet c nhng s thay i HasChanges() hay khng. Merge DataSet ny vi mt DataSet xc nh Merge() Cho php bn c d liu XML vo trong DataSet. ReadXml() ReadXmlSchema() Quay tr li mi s thay i gn nht i vi DataSet t khi n RejectChanges() c khi to hay AcceptChanges(). Cho php bn ghi ni dung ca mt DataSet ra XML. WriteXml() WriteXmlSchema() 7.6.3. Lm vic vi DataColumns Kiu DataColumn th hin mt ct n bn trong mt DataTable. DataColumn th hin s thit lp thng tin m hnh ca bng. Chng hn, m hnh bng Inventory ca CSDL AutoLot, s to ra bn DataColumns, vi mi ct (CarID, Make, Color, v PetName). Mi khi khi to cc i tng DataColumn, chng c thm vo trong colection Columns ca kiu DataTable (thng qua thuc tnh Column). Bng 7. 10: Cc thuc tnh ca DataColumn Properties ngha Thuc tnh ny c dng nu mt hng c th c gi tr null trong AllowDBNull ct ny. Gi tr mc nh l true. Nhng thuc tnh ny c dng cu hnh vic tng t ng AutoIncrement (autoincrement behavior) cho mt ct nht nh. iu N c dung Lu hnh ni b Trang 248

AutoIncrementSeed AutoIncrementStep Caption ColumnMapping

ColumnName

DataType DefaultValue Expression Ordinal ReadOnly Table Unique

khi chng ta mun bo m nhng gi tr l duy nht trong mt DataColumn . Theo mc nh, mt DataColumn khng h tr tng t ng. Thuc tnh ny dung thit lp caption s c hin th cho ct ny. Thuc tnh ny xc nh cch mt DataColumn c th hin khi mt DataSet c lu gi nh mt ti liu XML s dng phng thc DataSet.WriteXml(). Thuc tnh ny thit lp tn ca ct trong colection Columns. Nu khng t ColumnName r rng, th gi tr mc nh l Column vi hu t s ( n +1) ( v d., Column1, Column2, Column3,...). Thuc tnh ny nh ngha kiu d liu (Boolean, string, float,...) c lu gi trong ct. Thuc tnh ny thit lp gi tr mc nh c gn n ct khi chn nhng hng mi. Thuc tnh ny thit lp biu thc c s dng lc cc hng, tnh ton mt gi tr ca ct, hoc to ra mt ct kt hp. Thuc tnh ny a ra v tr ca ct trong colection Columns. Thuc tnh ny xc nh nu ch c sa i mt ln khi c thm vo bng. Mc nh l false. Thuc tnh ny a ra DataTable cha DataColumn. Thuc tnh ny thit lp mt gi tr cho bit c phi nhng gi tr trong mi hng ca ct l duy nht hay khng. Nu mt ct c gn mt rng buc kha chnh, thuc tnh Unique nn c thit lp l true.

Xy dng mt DataColumn Tip tc vi project SimpleDataSet cho ct CarID l kha chnh ca bng, cu hnh i tng DataColumn l read-only, duy nht, v khng null (s dng thuc tnh ReadOnly, Unique, v AllowDBNull).
private void MakeTable() { // Create a DataTable. DataTable table = new DataTable("Product"); // Create a DataColumn and set various properties. DataColumn column = new DataColumn(); column.DataType = System.Type.GetType("System.Decimal"); column.AllowDBNull = false; column.Caption = "Price"; column.ColumnName = "Price"; column.DefaultValue = 25; // Add the column to the table. table.Columns.Add(column); // Add 7 rows and set values. DataRow row; for(int i = 0; i < 7; i++) { row = table.NewRow();

Lu hnh ni b

Trang 249

row["Price"] = i + 1; // Be sure to add the new row to the // DataRowCollection. table.Rows.Add(row); } }

Cho php cc field tng t ng Mt kha cnh ca DataColumn l chng ta c th cu hnh tng t ng (autoincrement). Mt ct autoincrementing c s dng bo m rng khi mt hng mi c thm vo mt bng cho, gi tr ca ct ny c gn mt cch t ng trn c s tng dn. lm vic ny s dng nhng thuc tnh AutoIncrement, AutoIncrementSeed v AutoIncrementStep. Cho code sau cp nht cu trc ca carIDColumn DataColumn
private void AddAutoIncrementColumn()*{ DataColumn column = new DataColumn(); column.DataType = System.Type.GetType("System.Int32"); column.AutoIncrement = true; column.AutoIncrementSeed = 700; column.AutoIncrementStep = 7; // Add the column to a new DataTable. DataTable table = new DataTable("table"); table.Columns.Add(column); }

y, i tng carIDColumn c cu hnh bo m rng nhng dng c gi tr tng l 1. V gi tr khi u c thit lp l 0, nn ct ny s c nh s 0, 1, 2, 3, 7.6.4. Lm vic vi DataRows Mt colection ca cc i tng DataColumn th hin m hnh ca mt DataTable. Cn mt colection ca cc kiu DataRow i din cho d liu thc t trong bng. S dng nhng thnh phn ca lp DataRow, chng ta c th insert, remove, v thao tc nhng gi tr trong bng. Bng 7.11 trnh by mt vi thnh phn ca kiu DataRow. Bng 7. 11: Cc thnh phn chnh ca kiu DataRow. Members ngha Thuc tnh HasErrors tr v mt gi tr Boolean cho bit nu c li. HasErrors GetColumnsInError() Nh vy, phng thc GetColumnsInError() c s dng thu c nhng thnh phn li v GetColumnError c s dng thu GetColumnError() c s m t li, trong khi phng thc ClearErrors() loi b li ClearErrors() cho hng. Thuc tnh RowError cho php cu hnh mt s m t li RowError cho mt hng. ItemArray RowState GetChildRows GetParentRows Lu hnh ni b Thuc tnh ny thit lp tt c cc gi tr cho hng ny s dng mt mng cc i tng. Thuc tnh ny c dng xc nh " trng thi " hin thi ca DataRow. Tr v nhng dng con ca DataRow Tr v nhng dng cha ca DataRow Trang 250

Table AcceptChanges() RejectChanges() BeginEdit() EndEdit() CancelEdit() Delete()

Thuc tnh ny c dng thu c mt tham chiu ti DataTable cha DataRow. Nhng phng thc ny xc nhn hay loi b mi s thay i n hng t ln cui cng AcceptChanges() c gi. Nhng phng thc ny bt u, kt thc, hoc hy b mt thao tc hiu chnh trn mt i tng DataRow.

Phng thc ny nh du hng s c remove khi phng thc AcceptChanges() c gi. Phng thc ny a ra mt gi tr cho bit c phi ct c xc IsNull() nh cha mt gi tr null hay khng. 7.6.5. Lm vic vi DataTables Kiu DataTable nh ngha mt s ln cc thnh phn, nhiu thnh phn ca n ging v tn v chc nng ca DataSet. Bng 1.12 m t mt s thnh phn ct li ca kiu DataTable ngoi Rows v Columns. Bng 7. 12: Cc thnh phn chnh ca kiu DataTable Member ngha Cho bit chui bn trong bng c phn bit hoa/thng hay khng. Gi CaseSensitive tr mc nh l false. Tr v tp hp ca nhng quan h con cho DataTable ny (nu c) ChildRelations a ra tp hp ca nhng rng buc ca bng. Constraints Phng thc sao chp m hnh v d liu ca mt DataTable cho Copy() vo trong mt th hin mi. a ra DataSet m cha bng ny (nu c) DataSet a ra mt view mc nh ca bng. DefaultView MinimumCapacity a ra hay thit lp s lng hng ban u trong bng (mc nh l 5). a ra tp hp ca nhng quan h cha cho DataTable ny. ParentRelations Thit lp nhng ct m c chc nng kha chnh cho bng d liu. PrimaryKey Cho php bn nh ngha cch DataSet xut ni dung ca n ( nh phn RemotingFormat hay XML). Thit lp tn ca bng. TableName 7.6.6 Lm vic vi DataRelation Dataset lu tr nhng mi quan h trong i tng DataRelationCollection ca n. Mt mi quan h c biu din bi mt i tng DataRelation, kt hp nhng dng trong DataTable ny vi nhng DataTable khc Mi quan h (Relationship) cho php iu hng t mt bng n mt bng khc bn trong Dataset. Nhng thnh phn ch yu ca DataRelation l tn ca quan h, tn ca nhng bng quan h v nhng ct quan h trong mi bng. Mi quan h c th c xy dng vi nhiu hn mt ct cho mi bng bng cch ch ra mt mng cc i tng ca DataColumn nh l nhng ct chnh.. Khi mt quan h c thm vo DataRelationCollection, n c th thm vo mt UniqueKeyConstraint v mt ForeignKeyConstraint m bo tnh ton vn d liu khi c nhng thay i gi tr trn nhng ct quan h i tng DataRelation Lu hnh ni b Trang 251

Mt DataRelation c s dng quan h gia 2 i tng DataTable vi nhau thng qua i tng DataColumn. V d trong mi quan h khch hng v ho n, bng khch hng l cha v bng ho n l con trong mi quan h. Mi quan h c to ra gia nhng ct tng thch trong bng cha v bng con. l kiu d liu gia 2 ct l duy nht. Nhng mi quan h cng c th xp tng nhng thay i khc nhau t nhng dng d liu cha n nhng dng d liu con. iu khin cch gi tr b thay i trong nhng dng d liu con, ta thm vo mt ForeignKeyConstraint vo ConstraintCollection ca i tng DataTable. ConstraintCollection hot ng khi d liu trn bng cha b xo hay c cp nht. Khi mt DataRelation c to, u tin n kim tra xem mi quan h c to hay khng. Sau khi n c thm vo DataRelationCollection. Mi quan h c duy tr bi vic khng cho php bt k s thay i no m vi phm rng buc ny. Cc i tng DataRelation c cha trong DataRelationCollection. Bn c th truy cp DataRealtionCollection thng qua thuc tnh Collections ca DataSet v thuc tnh ChildRelation and ParentRelation ca DataTable Bng 7.13 m t mt s thnh phn ct li ca i tng DataRelation Thuc tnh Din t Tr v cc i tng DataColumns con ca quan h ny ChildColumns Tr v ForeignKeyConstraint cho quan h ChildKeyConstraint Tr v bng con ca quan h ChildTable Tr v Dataset cha DataRealtion ny DataSet Tr v tp hp m lu tr nhng thuc tnh tu chn ExtendedProperties Tr v hoc thit lp mt gi tr cho bit cc i tng Nested DataRelation l n Tr v mt mng i tng DataColumn m l nhng ct cha ParentColumns ca DataRelation ny Tr v UniqueConstraint m chc rng nhng gi tr trong ct ParentKeyConstraint cha ca DataRelation l duy nht Tr v hoc thit lp tn dng truy xut mt DataRelation RelationName t DataRelationCollection Th d : To trang TableRelationships.aspx cho php thit lp cc mi lin kt. - Mi lin kt ca hai bng Authors(Tc gi) v TitleAuthor(Ta sch ca Tc gi) theo vng kho lin kt l au_id (M Tc gi)
DataRelation Authors_TitleAuthor = new DataRelation("Authors_TitleAuthor", dsPubs.Tables["Authors"].Columns["au_id"], dsPubs.Tables["TitleAuthor"].Columns["au_id"]);

- Mi lin kt ca hai bng Titles(Ta sch) v TitleAuthor(Ta sch ca Tc gi) theo vng kho lin kt l title_id (M sch)
DataRelation Titles_TitleAuthor = new DataRelation("Titles_TitleAuthor", dsPubs.Tables["Titles"].Columns["title_id"], dsPubs.Tables["TitleAuthor"].Columns["title_id"]); Ni dung thit k trang TableRelationships.aspx

c iu khin nhn cha danh sch tng tc gi v cc ta sch ca tc gi nu c.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TableRelationships.aspx.cs" Inherits="TableRelationships" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

Lu hnh ni b

Trang 252

<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lblList" runat="server" EnableViewState="False"></asp:Label> </div> </form> </body> </html>

Phn m lnh:
public partial class TableRelationships : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack){ CreateList(); } } private string connectionString = WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString; private void CreateList() { // Define ADO.NET objects. string selectSQL = "SELECT au_lname, au_fname, au_id FROM Authors"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(selectSQL, con); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet dsPubs = new DataSet(); try { con.Open(); adapter.Fill(dsPubs, "Authors"); // This command is still linked to the data adapter. cmd.CommandText = "SELECT au_id, title_id FROM TitleAuthor"; adapter.Fill(dsPubs, "TitleAuthor"); // This command is still linked to the data adapter. cmd.CommandText = "SELECT title_id, title FROM Titles"; adapter.Fill(dsPubs, "Titles"); } catch (Exception err) { lblList.Text = "Error reading list of names. "; lblList.Text += err.Message; } finally { con.Close(); } DataRelation Titles_TitleAuthor = new DataRelation("Titles_TitleAuthor",

Lu hnh ni b

Trang 253

dsPubs.Tables["Titles"].Columns["title_id"], dsPubs.Tables["TitleAuthor"].Columns["title_id"]); DataRelation Authors_TitleAuthor = new DataRelation("Authors_TitleAuthor", dsPubs.Tables["Authors"].Columns["au_id"], dsPubs.Tables["TitleAuthor"].Columns["au_id"]); dsPubs.Relations.Add(Titles_TitleAuthor); dsPubs.Relations.Add(Authors_TitleAuthor); foreach (DataRow rowAuthor in dsPubs.Tables["Authors"].Rows) { lblList.Text += "<br /><b>" + rowAuthor["au_fname"]; lblList.Text += " " + rowAuthor["au_lname"] + "</b><br />"; foreach (DataRow rowTitleAuthor in rowAuthor.GetChildRows(Authors_TitleAuthor)) { foreach (DataRow rowTitle in rowTitleAuthor.GetParentRows(Titles_TitleAuthor)) { lblList.Text += "&nbsp;&nbsp;"; lblList.Text += rowTitle["title"] + "<br />"; } } } } }

Kt qu thc thi lit k danh sch cc tc gi v cc ta sch ca tc gi c trong CSDL:

Lu hnh ni b

Trang 254

7.6.7 Xut cc i tng DataTable/ DataSet ra XML C DataSet ln DataTables h tr cc phng thc WriteXml() V ReadXml(). WriteXml() cho php bn ghi ni dung ca i tng ra mt file XML. ReadXml() Cho php bn c ni dung mt DataSet (hay DataTable) t mt ti liu XML cho. Ngoi ra, c DataSets v DataTables h tr WriteXmlSchema() v ReadXmlSchema() lu tr hoc load mt file *.xsd. static void DataSetAsXml(DataSet carsInventoryDS) { // Save this DataSet as XML. carsInventoryDS.WriteXml("carsDataSet.xml"); carsInventoryDS.WriteXmlSchema("carsDataSet.xsd"); // Clear out DataSet. carsInventoryDS.Clear(); // Load DataSet from XML file. carsInventoryDS.ReadXml("carsDataSet.xml"); } Nu m file carsDataSet.xml (nm trong folder bin\Debug ca project), chng ta s nhn thy mi ct trong bng c m ha nh mt th ca XML: <?xml version="1.0" standalone="yes"?> <Car_x0020_Inventory> <Inventory> <CarID>0</CarID> <Make>BMW</Make> <Color>Black</Color> <PetName>Hamlet</PetName> </Inventory> <Inventory> <CarID>1</CarID> <Make>Saab</Make> <Color>Red</Color> <PetName>Sea Breeze</PetName> </Inventory> </Car_x0020_Inventory> 7.7 i tng d liu SqlDataSource SqlDataSource Control cho php kt ni n c s d liu quan h MS SQL Server. SQLDataSource t ng pht sinh cc lnh : Insert, Update, Delete, Select v lc d liu, sp xp, phn trang ,Chng ta s s dng control ny vi cc Data Controls trong cc chng sau y. Th d: To SqlDataSource s dng Wizard Lu hnh ni b Trang 255

Thit k giao din trang gm i tng d liu SqlDataSource v GridView (trong th Data ca hp cng c).

Cu hnh lm vic cho SqlDataSource

Xut hin hp thoi Configure Data Source, click nt New Connection to kt ni mi :

Xut hin hp thoi

Lu hnh ni b

Trang 256

Nhp tn SQL Server trong khung Server Name. Chn ng nhp vo SQL theo chng thc Windows Authentication hoc SQL Authentication (nhp User ID v Password). Nu kt ni SQL Server c, tip n s chn CSLD trong ComboBox [Select or Enter database name ;] Click nt OK hon tt bc to kt ni. Mn hnh quay li hp thoi Configure Data Source. Click [+Connection String] s thy ni dung chui kt ni va to nh hnh di y:

Lu hnh ni b

Trang 257

Click nt [Next], chuyn sang hp thoi k tip cho php chn hay nhp li tn chui kt ni. Chui ConnectionString ny s c ghi vo tp tin Web.config.
<connectionStrings> <add name="NorthwindConnectionString" connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=Northwind;User ID=sa;Password=123456" providerName="System.Data.SqlClient" /> </connectionStrings>

Click nt [Next] chuyn sang mn hnh chn bng d liu hoc th tc lu tr (store procedure). Ta chn bng Products, v chn ba vng ProductID, ProductName, UnitPrice cho SqlDataSource. Cu lnh truy vn tng ng c to ra :

Lu hnh ni b

Trang 258

Click nt [WHERE] to b lc cho cu truy vn SELECT. Click nt [Advanced..] to thm cc cu lnh truy vn Insert, Delete, Update cho cu trc SqlDataSource.

Click nt [Next] chuyn sang phn Test Query. Click nt [Test Query] s c kt qu truy vn hin th trong khung hp thoi tng ng vi lnh Select. Lu hnh ni b Trang 259

Click nt [Finish] kt thc. Phn m lnh thit k SqlDataSource c ni dung sau:


<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products]" ConflictDetection="CompareAllValues" DeleteCommand="DELETE FROM [Products] WHERE [ProductID] = @original_ProductID AND [ProductName] = @original_ProductName AND (([UnitPrice] = @original_UnitPrice) OR ([UnitPrice] IS NULL AND @original_UnitPrice IS NULL))" InsertCommand="INSERT INTO [Products] ([ProductName], [UnitPrice]) VALUES (@ProductName, @UnitPrice)" UpdateCommand="UPDATE [Products] SET [ProductName] = @ProductName, [UnitPrice] = @UnitPrice WHERE [ProductID] = @original_ProductID AND [ProductName] = @original_ProductName AND (([UnitPrice] = @original_UnitPrice) OR ([UnitPrice] IS NULL AND @original_UnitPrice IS NULL))"> <DeleteParameters> <asp:Parameter Name="original_ProductID" Type="Int32" /> <asp:Parameter Name="original_ProductName" Type="String" /> <asp:Parameter Name="original_UnitPrice" Type="Decimal" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> <asp:Parameter Name="original_ProductID" Type="Int32" /> <asp:Parameter Name="original_ProductName" Type="String" />

Lu hnh ni b

Trang 260

<asp:Parameter Name="original_UnitPrice" Type="Decimal" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> </InsertParameters> </asp:SqlDataSource>

Sau thc hin vic gn thuc tnh DataSoure ca GridView vi i tng SqlDataSource nh hnh sau. Cc kim tra [X] Enable Paging/Sorting/Editing/Deleting/Selection cho php GridView thc hin phn trang/sp xp/cp nht/xa/chn d liu trong bng Produtcs. Ni dung ny s c cp r trong Chng 9.

Phn m lnh thc thi trang :


public partial class SqlDataSourcePage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.SqlDataSource1.ConnectionString = WebConfigurationManager.ConnectionStrings[ "NorthwindConnectionString"].ConnectionString; } }

Kt qu thc thi :

Lu hnh ni b

Trang 261

Tng kt Chng ny trnh by chi tit lp ngt kt ni ca ADO.NET. Trung tm ca lp ngt kt ni l DataSet. Kiu ny th hin nhng bng, nhng quan h, nhng rng buc, n c th c xem nh mt Database trong b nh.

Lu hnh ni b

Trang 262

BI TP CHNG 7: Bi 1: Thc hnh li cc th d trong bi hc n li ni dung va hc. Bi 2: To 1 trang ASP.Net tn XemDanhSachLoaiMatHang.aspx , gm 1 ListView control t tn lvDanhSachLoaiMatHang.

Bc 1 . Nhp vo biu tng trn ListView control chn New data source ca s DataSource Configuration Wizard xut hin . Sau chn Database v t tn ID l DBLoaiMatHang nh hnh bn di , nhp OK .

Bc 2 . Trn ca s Configure Data Source | New Connection v thit lp cc thng s trong ca s Add Connection nh hnh sau .

Lu hnh ni b

Trang 263

nhp OK tr v ca s Configure Data Source | nhp Next , xut hin thng bo lu thng tin kt ni c s d liu vo trong tp tin cu hnh Web.config | nhp Next | chn cc ct | nhn Advanced...

Bc 3 . Trn ca s Advanced SQL Generation Options | Generate INSERT,UPDATE, and DELETE statements | OK . Tip tc nhn Next | Test Query kim tra d liu | nhn Finish hon tt.

Lu hnh ni b

Trang 264

Bc 4 . Nhp vo biu tng trn ListView control | Configure ListView, ca s Configure ListView xut hin v thit lp nh hnh di , nhn OK hon tt.

Lu hnh ni b

Trang 265

Bc 5 . Nhn Ctrl+F5 thi hnh ng dng , kt qu nh hnh bn .

Lu hnh ni b

Trang 266

Chng 8 :

Tm hiu v ng dng c ch Data Binding

Cc vn chnh s c cp : Gii thiu Data Binding. Cc dng Data Binding. Kt thc chng ny cc bn c th : S dng k thut DataBinding vi cc i tng d liu (data controls) trong ng dng ASP.NET 8.1 Gii thiu DataBinding ASP.NET cung cp cho chng ta rt nhiu iu khin cho php hin th cng nh tip nhn thng tin t ngi dng. C nhng iu khin cho php chng ta hin th nhng thng tin tnh (Static tc l gi tr xc nh c ngay khi lp trnh), mt s hin th c c nhng thng tin ng (Dynamic - tc l c tnh ton khi chy chng trnh). vic hin th thng tin ng ny mt cch n gin v nhanh chng, ASP.NET cung cp cho chng ta mt c tnh gi l "Data Binding" (kt ni d liu). Data Binding l mt k thut kt ni d liu vi nhng i tng. S dng data binding, bn c th ni d liu trong mt ngun d liu n mt i tng ngi dng. Mi vic thay i trn cc i tng giao din ngi dng c th trc tip c cp nht vo ngun d liu. T "data" cng cn phi c hiu theo ngha rng, n khng nht thit phi l ci g lin quan n C s d liu nh ta thng ngh m c th l mt thuc tnh, mt mng, mt tp hp, mt danh sch, mt trng d liu trong bng CSDL.hay tng qut l mt biu thc tr v gi tr. C hai kiu binding d liu l Simple Data Binding v Repeated Data Binding. Chng ta quan tm nhiu n kiu th hai Repeated Data Binding - vi ngun d liu c truy xut t c s d liu. 8.2 Cc dng Data Binding 8..2.1 Dng kt ni d liu n (Single Data Binding) Trong ASP.NET, c th gn mt gi tr n l vo trang c gi l Single Data Binding. C php gn d liu n vo trang nh sau: <%# biu_thc %> Trong : biu_thc c th l mt hng, mt bin, mt hm, mt biu thc hoc c th l mt thuc tnh khc. Mt s cch dng dng kt ni d liu n: Hng s: <%# 20 %> <br /> Hng xu: <%# "Xin cho" %> <br /> Biu thc: <%# 10+5 %> <br /> Hm : <%# "Sin(3.14/2) = " + Math.Sin(3.14/2) %> <br /> Thuc tnh khc: <%# "Tiu ca trang l " + this.Title %> C th gn kt ti mt biu thc, mt bin, thuc tnh bt k. Ch : Trong th tc Page_Load cn thm lnh this.DataBind() thc s gn kt. Th d 1: To trang SimpleDataBinding.aspx minh ha dng kt ni d liu n gin. Phn m lnh thit k trang SimpleDataBinding.aspx trong c s dng dng kt ni d liu n gin vi bin TransactionCount. Lu hnh ni b Trang 267

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SimpleDataBinding.aspx.cs" Inherits="SimpleDataBinding" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Simple Data Binding</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblDynamic" runat="server" Font-Size="X-Large" > There were <%# TransactionCount %> transactions today. I see that you are using <%# Request.Browser.Browser %>. </asp:Label> </div> </form> </body> </html> Phn m lnh thc thi trang SimpleDataBinding.aspx.cs: public partial class SimpleDataBinding : System.Web.UI.Page { protected int TransactionCount; protected void Page_Load(object sender, EventArgs e) { // (You could use database code here // to look up a value for TransactionCount.) TransactionCount = 10; // Now convert all the data binding expressions on the page. this.DataBind(); } }

Kt qu thc thi trang SimpleDataBinding.aspx:

8..2.2 Dng kt ni d liu c s lp li (Repeated Data Binding) C rt nhiu trng hp d liu cn hin th l mt danh sch (nh mng, bng, DataReader,) hay tng qut l mt tp hp cc mc (Collection Items ). Trong trng hp nh vy, hon ton c th dng c ch DataBinding trong ASP.NET gn kt qu vo mt iu khin dng danh sch (nh ListBox, DropdownList, CheckboxList,) hin th m khng cn phi vit nhiu dng code. Cc iu khin cho php gn kt d liu thng c ba thuc tnh vi cc ngha nh sau: DataSource: L thuc tnh ch n ngun d liu cn gn kt. Ngun d liu ny phi l mt tp hp. V d: DataTabe, Array, Lu hnh ni b Trang 268

DataSourceID: Ch n mt i tng cung cp ngun d liu. C th s dng hoc thuc tnh DataSourceID hoc DataSource nhng khng c c hai. DataTextField: Cho bit l gn kt vi trng no ca mi mc d liu. Th d 2: To trang ListDataBinding.aspx minh ha kt ni d liu dng Repeated Data Binding Phn m lnh thit k trang ListDataBinding.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListDataBinding.aspx.cs" Inherits="ListDataBinding" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:ListBox id="MyListBox" runat="server" Width="197px" Height="193px"></asp:ListBox> <br /><br /> <select id="MyHTMLSelect" size="1" runat="server"/> <br /><br /> <asp:DropDownList id="MyDropDownListBox" runat="server" Width="248px" Height="22px"></asp:DropDownList> <br /><br /> <asp:CheckBoxList id="MyCheckBoxList" runat="server" Width="201px" Height="157px"></asp:CheckBoxList> <br /><br /> <asp:RadioButtonList id="MyRadioButtonList" runat="server" Width="249px" Height="158px"></asp:RadioButtonList> </div> </form> </body> </html> Phn m lnh thc thi trang ListDataBinding.aspx.cs: public partial class ListDataBinding : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Create and fill the collection. List<string> fruit = new List<string>(); fruit.Add("Kiwi"); fruit.Add("Pear"); fruit.Add("Mango"); fruit.Add("Blueberry"); fruit.Add("Apricot"); fruit.Add("Banana"); fruit.Add("Peach"); fruit.Add("Plum");

Lu hnh ni b

Trang 269

// Define the binding for the list controls. MyListBox.DataSource = fruit; MyDropDownListBox.DataSource = fruit; MyHTMLSelect.DataSource = fruit; MyCheckBoxList.DataSource = fruit; MyRadioButtonList.DataSource = fruit; // Activate the binding. this.DataBind(); } }

Kt qu thc thi cho thy r s kt ni d liu t tp d liu List<string> n cc iu khin d liu ca ASP.NET :

Ch : nu khng c pht biu this.DataBind() th s khng c kt qu nh trn. Th d 3: To trang DataSetBinding.aspx lin kt d liu ListBox vi i tng ADO.NET l DataSet Phn m lnh thit k trang DataSetBinding.aspx: Lu hnh ni b Trang 270

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataSetBinding.aspx.cs" Inherits="DataSetBinding" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:ListBox ID="lstUser" runat="server" Height="152px" Width="192px"></asp:ListBox></div> </form> </body> </html> Phn m lnh thc thi trang DataSetBinding.aspx.cs: public partial class DataSetBinding : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Define a DataSet with a single DataTable. DataSet dsInternal = new DataSet(); dsInternal.Tables.Add("Users"); // Define two columns for this table. dsInternal.Tables["Users"].Columns.Add("Name"); dsInternal.Tables["Users"].Columns.Add("Country"); // Add some actual information into the table. DataRow rowNew = dsInternal.Tables["Users"].NewRow(); rowNew["Name"] = "John"; rowNew["Country"] = "Uganda"; dsInternal.Tables["Users"].Rows.Add(rowNew); rowNew = dsInternal.Tables["Users"].NewRow(); rowNew["Name"] = "Samantha"; rowNew["Country"] = "Belgium"; dsInternal.Tables["Users"].Rows.Add(rowNew); rowNew = dsInternal.Tables["Users"].NewRow(); rowNew["Name"] = "Rico"; rowNew["Country"] = "Japan"; dsInternal.Tables["Users"].Rows.Add(rowNew); // Define the binding. lstUser.DataSource = dsInternal.Tables["Users"]; lstUser.DataTextField = "Name";

Lu hnh ni b

Trang 271

// Define the binding. lstUser.DataSource = dsInternal; lstUser.DataMember = "Users"; lstUser.DataTextField = "Name"; this.DataBind(); // Could also use lstItems.DataBind() to bind just the list box. } }

Kt qu thc thi:

Lu hnh ni b

Trang 272

BI TP CHNG 8: Bi 1: Thc hin cc bi tp th d trong bi hc nm vng ni dung ca bi. Bi 2: To trang ASP.NET kt ni d liu vi i tng nh Image:
<asp:Image id="imgDynamic" ImageUrl="<%# URL %>" runat="server" />

i tng Label:
<asp:Label id="lblDynamic" runat="server"><%# URL %></asp:Label>

i tng CheckBox:
<asp:CheckBox id="chkDynamic" Text="<%# URL %>" runat="server" />

i tng HyperLink:
<asp:Hyperlink id="lnkDynamic" Text="Click here!" NavigateUrl="<%# URL %>" runat="server" />

Phn m lnh thit k trang DataBindingUrl.aspx:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataBindingUrl.aspx.cs" Inherits="DataBindingUrl" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblDynamic" runat="server"><%# URL %></asp:Label> <br /><br /> <asp:CheckBox id="chkDynamic" Text="<%# URL %>" runat="server" /> <br /><br /> <asp:Hyperlink id="lnkDynamic" Text="Click here!" NavigateUrl="<%# URL %>" runat="server" /> <br /><br /> <asp:Image id="imgDynamic" ImageUrl="<%# URL %>" runat="server" /> </div> </form> </body> </html>

Phn m lnh thc thi trang:


public partial class DataBindingUrl : System.Web.UI.Page { public string URL; protected void Page_Load(Object sender, EventArgs e) { URL = "Images/picture.jpg";

Lu hnh ni b

Trang 273

this.DataBind(); } }

Kt qu thc thi:

Bi 3: To trang ASP.NET RecordEditor.aspx gn kt d liu ca bng Product trong CSDL Northwind vi cc iu khin d liu Label v ListBox trn trang. Phn m lnh thit k trang RecordEditor.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RecordEditor.aspx.cs" Inherits="RecordEditor" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Record Editor</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList ID="lstProduct" runat="server" AutoPostBack="True" Width="280px" OnSelectedIndexChanged="lstProduct_SelectedIndexChanged"> </asp:DropDownList> <br /> <br /> <hr /> <br /> <table> <tr> <td style="width: 234px" valign="top"> <asp:Label ID="lblRecordInfo" runat="server"></asp:Label></td> <td style="width: 190px"> <asp:Panel ID="pnlCategory" runat="server" Visible="False"> <asp:ListBox ID="lstCategory" runat="server" Height="120px" Width="152px"> </asp:ListBox><br /> <br /> <asp:Button ID="cmdUpdate" runat="server" Text="Update" OnClick="cmdUpdate_Click" />

Lu hnh ni b

Trang 274

</asp:Panel> </td> </tr> </table> </div> </form> </body> </html>

Phn m lnh thc thi trang RecordEditor.aspx.cs:


public partial class RecordEditor : System.Web.UI.Page { private string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { // Define the ADO.NET objects for selecting Products. string selectSQL = "SELECT ProductName, ProductID FROM Products"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(selectSQL, con); // Open the connection. con.Open(); // Define the binding. lstProduct.DataSource = cmd.ExecuteReader(); lstProduct.DataTextField = "ProductName"; lstProduct.DataValueField = "ProductID"; // Activate the binding. lstProduct.DataBind(); con.Close(); // Make sure nothing is currently selected. lstProduct.SelectedIndex = -1; } } protected void lstProduct_SelectedIndexChanged(object sender, EventArgs e) { // Create a command for selecting the matching product record. string selectProduct = "SELECT ProductName, QuantityPerUnit, " + "CategoryName FROM Products INNER JOIN Categories ON " + "Categories.CategoryID=Products.CategoryID " + "WHERE ProductID=@ProductID"; // Create the Connection and Command objects. SqlConnection con = new SqlConnection(connectionString); SqlCommand cmdProducts = new SqlCommand(selectProduct, con);

Lu hnh ni b

Trang 275

cmdProducts.Parameters.AddWithValue("@ProductID", lstProduct.SelectedItem.Value); // Retrieve the information for the selected product. using (con) { con.Open(); SqlDataReader reader = cmdProducts.ExecuteReader(); reader.Read(); // Update the display. lblRecordInfo.Text = "<b>Product:</b> " + reader["ProductName"] + "<br />"; lblRecordInfo.Text += "<b>Quantity:</b> " + reader["QuantityPerUnit"] + "<br />"; lblRecordInfo.Text += "<b>Category:</b> " + reader["CategoryName"]; // Store the corresponding CategoryName for future reference. string matchCategory = reader["CategoryName"].ToString(); // Close the reader. reader.Close(); // Create a new Command for selecting categories. string selectCategory = "SELECT CategoryName, CategoryID FROM Categories"; SqlCommand cmdCategories = new SqlCommand(selectCategory, con); // Retrieve the category information, and bind it. lstCategory.DataSource = cmdCategories.ExecuteReader(); lstCategory.DataTextField = "CategoryName"; lstCategory.DataValueField = "CategoryID"; lstCategory.DataBind(); // Highlight the matching category in the list. lstCategory.Items.FindByText(matchCategory).Selected = true; } pnlCategory.Visible = true; } protected void cmdUpdate_Click(object sender, EventArgs e) { // Define the Command. string updateCommand = "UPDATE Products " + "SET CategoryID=@CategoryID WHERE ProductID=@ProductID"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(updateCommand, con); cmd.Parameters.AddWithValue("@CategoryID", lstCategory.SelectedItem.Value); cmd.Parameters.AddWithValue("@ProductID", lstProduct.SelectedItem.Value); // Perform the update. using (con) { con.Open(); cmd.ExecuteNonQuery(); } } }

Kt qu thc thi: Lu hnh ni b Trang 276

u tin hin th ni dung mt DropdownList:

Khi chn gi tr trong DropdownList trn s gy ra s kin


lstProduct_SelectedIndexChanged(object sender, EventArgs e) v s hin th kt qu la

chn :

thy gi tr trong ListBox ang chn cha thng tin Category ca mu tin Product va c chn. Nu thay i gi tr khc v click nt Update d liu mi thay i ca vng Category trn mu tin hin ti s c cp nht li v hin ra ln chn sau.

Kt qu hin ra ngay sau khi chn li sn phm ny.

Lu hnh ni b

Trang 277

Chng 9: Cc i tng d liu (Data Controls)


Cc bn cn trnh by c cc vn sau : Cc c im ca ADO.Net . Kt ni c s d liu s dng i tng SQLDataSource Control Thc thi c rng buc d liuvi cc DataControls: GridView, DataList, ListView,... 9.1 i tng d liu GridView GridView c l l mt iu khin trnh din d liu quan trng nht ca ASP.NET. N cho php gn v hin th d liu dng bng, trong mi hng l mt bn ghi, mi ct ng vi mt trng d liu. Ngoi vic hin th, GridView cn c rt nhiu tnh nng khc m trc y ngi ta phi vit rt nhiu dng code mi c c, Th d: nh dng, phn trang, sp xp, sa i, xa d liu. GridView c th gn kt d liu vi cc ngun nh DataReader, SqlDataSource, ObjectDataSource hay bt k ngun no c ci t System.CollectionsEnumerable. Trong bi hc ny, chng ta s i tm hiu v s dng mt s tnh nng ni bt ca GridView, t c th p dng lm Project cho mn hc. 9.1.1 Tm hiu lp GridView 9.1.2 Cc thuc tnh v ct thuc tnh GridView ngoi vic hin th thun ty cc trng ca mt ngun d liu, n cn cho php hin th di cc hnh thc khc (Th d di dng nt, dng HyperLink, dng checkbox), cc ct khc b tr cho vic thao tc d liu nh Select, Update, Delete hon ton c th ty bin trong GridView. chnh sa cc ct dng ny, click chn "smart tag" ca GridView v chn "Edit Field" hoc chn thuc tnh Columns ca GridView trong ca s thuc tnh. Loi ct BoundField ButtonField M t Hin th gi tr ca mt trng thuc ngun d liu. Hin th mt nt lnh cho mi mc trong GridView. Nt ny cho php bn c th to ra cc nt ty bin kiu nh Add hay Remove. Hin th mt checkbox ng vi mi mc trong GridView. Ct ny thng c dng hin th cc trng kiu Boolean (Yes/No). Hin th cc nt lnh c nh ngha sn thc hin cc thao tc select, edit, hay delete. Hin th gi tr ca mt trng di dng siu lin kt (hyperlink). Loi ct ny cho php bn gn mt trng th hai vo URL ca siu lin kt. Hin th mt nh ng vi mi mc trong GridView.

CheckBoxField

CommandField

HyperLinkField

ImageField

Lu hnh ni b

Trang 278

TemplateField Cc thuc tnh

Hin th ni dung ty bin ca ngi dng cho mi mc d liu trong GridView, theo nh mu nh sn. Loi ct ny cho php ta to ra cc ct ty bin.

Thuc tnh GridLines ShowHeader ShowFooter PageSize PageCount PageIndex AllowPaging AllowSorting AutoGenerateColumns AutoGenerateDeleteButton AutoGenerateUpdateButton AutoGenerateSelectButton EditIndex (SelectedIndex) SelectedIndex Rows Columns

M t n, hin cc ng vin ca GridView. Cho php Hin/ n phn Header Cho php Hin/ n phn Footer Get/Set cho bit mi trang cha bao nhiu dng. Cho bit s trang ca ngun d liu m n gn kt Get/Set ch s ca trang ang c hin th C cho php phn trang khng ( true = c) C cho php sp xp khng (true=c) C t ng sinh ra cc ct ng vi cc ct trong ngun d liu hay khng ? Mc nh = true (c) T ng to ra ct Delete (true = t ng) T ng to ra ct Update (true = t ng) T ng to ra ct Select (true = t ng) t hng no v ch edit. EditIndex = 2 hng th 3 (ch s 2) s v ch edit. Nu t EditIndex = -1 th s thot khi ch Edit. Tr v ch s ca dng ang chn Mt tp hp cha cc hng ca GridView. Mt tp hp cha cc ct ca GridView.

9.1.3 Cc style p dng cho GridView GridView rt linh hot trong vic trnh by d liu, n cho php ta nh dng cc phn thng qua style. Th d ta c th nh dng cho phn Header, Footer, cc mc d liu, cc hng chn-l v.v Bng di y s gii thch r ngha mt s thuc tnh:

Lu hnh ni b

Trang 279

Thuc tnh style

M t

Style p dng cho cc hng d liu chn-l trong GridView. Khi AlternatingRowStyle t thuc tnh ny th cc hng s c hin th vi nh dng lun phin gia RowStyle v AlternatingRowStyle. EditRowStyle FooterStyle HeaderStyle PagerStyle Style hin th hng hin ang c sa (Edit). Style p dng cho phn Footer. Style p dng cho phn Header. Style p dng cho phn phn trang (cc trang << 1 2 3 >>). Style p dng cho cc hng d liu trong GridView control. Khi AlternatingRowStyle c thit lp th s p dng lun phin gia RowStyle v AlternatingRowStyle.

RowStyle

Style p dng cho hng ang c chn (Selected)ca GridView. SelectedRowStyle 9.1.4 Cc s kin GridView c rt nhiu s kin quan trng, cc s kin ny khi kch hot s cung cp cho ta nhng thng tin hu ch trong qu trnh x l. Th d, khi chng ta click nt Update, n s kch hot s kin Updating v tr v cho chng ta cc gi tr m ngi dng va sa. Di y l bng tng hp mt s s kin hay dng nht: Tn s kin M t

PageIndexChanged

Xut hin khi ta click chn cc nt ( << 1 2 3 >>) trong hng phn trang. Xut hin khi ngi dng click chn cc nt ( << 1 2 3 >>) trong hng phn trang nhng TRC khi GridView thc hin vic phn trang. Ta c th hy vic phn trang ti s kin ny. Xut hin khi nt Cancel c click nhng trc khi thot khi ch Edit. Xut hin khi mt nt c click. Xut hin khi mt hng mi c to ra. Thng c s dng sa ni dung ca hng khi n va c to ra. Xut hin khi mt hng d liu c gn vo GridView. Ti y ta c th sa i ni dung ca hng . Xut hin khi nt Delete ca mt hng c click, nhng sau khi GridView delete bn ghi t ngun. Trang 280

PageIndexChanging

RowCancelingEdit

RowCommand

RowCreated

RowDataBound

RowDeleted Lu hnh ni b

RowDeleting

Xut hin khi nt Delete c click nhng trc khi GridView xa bn ghi t ngun. Ti y c th Cancel vic Delete. Xut hin khi nt Edit c click, nhng trc khi GridView v ch sa. Xut hin khi nt Update c click, nhng sau khi GridView update hng d liu. Xut hin khi nt Update c click, nhng trc khi GridView update hng d liu. Xut hin khi nt Select ca hng c click nhng sau khi GridView x l xong thao tc Select.

RowEditing

RowUpdated

RowUpdating

SelectedIndexChanged

SelectedIndexChanging Xut hin khi nt Select ca hng c click nhng trc khi GridView x l xong thao tc Select. Sorted Xut hin khi Hyperlink (tiu ct) c click, nhng sau khi GridView thc hin vic sp xp. Xut hin khi Hyperlink (tiu ct) c click, nhng trc khi GridView thc hin vic sp xp. S kin ny khi xy ra, n s cung cp cho chng ta thng tin v tn ct va c click. Da vo ta c th thc hin vic sp xp mt cch d dng.

Sorting

9.1.5 Cc phng thc Tn phng thc DataBind() M t Gn kt d liu gia GridView v ngun d liu (t cc thuc tnh DataSource, DataTextField hoc DataSourceID. Xa mt dng trong GridView Cp nht mt dng trong GridView.

DeleteRow(int) UpdateRow(int i, bool Valid) Sort(Biu thc sx, hng sx)

Sp xp da trn biu thc v hng.

9.1.6 Cc tnh nng h tr ca GridView 9.1.6.1 Phn trang thc hin phn trang, cn t thuc tnh AllowPaging = True. Khi phn trang, c th ty bin hin th cc trang (hin th dng cc s 1 2 3 hay mi tn << >>) bng cch t cc thuc tnh con trong PagerSettings. Lu hnh ni b Trang 281

p ng vi thao tc click nt chuyn trang gy ra s kin PageIndexChanging trn GridView. Bt buc trong phng thc y thc phi c dng lnh GridView1.PageIndex=
e.NewPageIndex; protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex= e.NewPageIndex; .. }

9.1.6.2 Tnh nng t ng sp xp Tnh nng ny cho php d liu trong GridView s t ng c sp xp theo gi tr ca ct m ngi dng click. y ta c th sp xp theo chiu tng (Asscending) hoc gim (Descending). bt tnh nng ny, cn t thuc tnh AllowSorting = true trong GridView. Khi ngi dng click chut vo mt ct tiu no ca GridView th s kin Sorting s c kch hot, ti y ta cn phi ch r cho GridView bit l sp theo ct no (SortExpression ) v theo chiu tng hay gim (SortDirection).
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CaptionAlign="Right"

Lu hnh ni b

Trang 282

CellPadding="4" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5" AllowSorting="True" CellSpacing="2" ForeColor="Black" OnSorting="GridView1_Sorting"> <PagerSettings FirstPageText="FirstPage" LastPageText="LastPage" NextPageText="Next" PageButtonCount="5" Position="TopAndBottom" PreviousPageText="Previous" /> <FooterStyle BackColor="#CCCCCC" /> <RowStyle BackColor="White" /> <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" Wrap="False" /> <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" /> </asp:GridView>

Phng thc p ng s kin Sorting:


protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { bool sortAscending = (ViewState["SortAscending"]==null)? true:(bool)ViewState["SortAscending"]; if (sortAscending) { e.SortDirection = SortDirection.Ascending; sortAscending = false; } else { e.SortDirection = SortDirection.Descending; sortAscending = true; } // do something ViewState["SortAscending"]= sortAscending; }

9.1.6.3 Cc mu hin th - Template ASP.NET cung cp cho chng ta sn mt s Template (mu) hin th GridView cng kh p. V vy, bn c th s dng ngay cc template ny khi xy dng ng dng. Cch thc chn template cho GridView nh sau: b1: M trang ch Design b2: Chn GridView v chn smart tag, tip theo chn AutoFormat

Lu hnh ni b

Trang 283

b3: Chn Format trong danh sch. T hp mu c chn t Template c sn. Sau khi chn Template, ASP.NET s t ng to ra cc thuc tnh (th) tng ng trong GridView, ti y bn c th tip tc ty bin thm theo nh mun.

9.1.7 To cc ct ty bin HyperLink, BoundColunm 9.1.7.1 To ct BoundField th cng to cc ct th cng, cn t thuc tnh AutoGenerateColumns = "False", sau son th cng cc ct trong ca s Edit Columns. 9.1.7.2 To mt ct HyperlinkField To trang ASP.NET GridViewAndHyperLinkPage.aspx s dng GridView c ct loi HyperLinkField. Phn m lnh thit k trang GridViewAndHyperLinkPage.aspx :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewAndHyperLinkPage.aspx.cs" Inherits="GridViewAndHyperLinkPage" %> <!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 runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div>

Lu hnh ni b

Trang 284

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"> <Columns> <asp:HyperLinkField DataNavigateUrlFields="RecruiterID" DataNavigateUrlFormatString="~/Details.aspx?RecruiterID={0}" DataTextField="Email" HeaderText="Email"> <HeaderStyle HorizontalAlign="Left" /> </asp:HyperLinkField> <asp:BoundField DataField="CompanyName" HeaderText="Ten Cong Ty"> <HeaderStyle HorizontalAlign="Left" /> </asp:BoundField> <asp:BoundField DataField="ContactName" HeaderText="Lien He"> <HeaderStyle HorizontalAlign="Left" /> </asp:BoundField> <asp:CheckBoxField DataField="Activate" HeaderText="#" /> </Columns> </asp:GridView> </div> </form> </body> </html>

Phn m lnh thc thi trang GridViewAndHyperLinkPage.aspx.cs


public partial class GridViewAndHyperLinkPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { FillData(GridView1); } void FillData(GridView gridView) { SqlDataSource sqlDataSource = new SqlDataSource(); sqlDataSource.ConnectionString = WebConfigurationManager.ConnectionStrings[ "RecruitVietnamDbConnectionString" ].ConnectionString; sqlDataSource.SelectCommandType = SqlDataSourceCommandType.Text; sqlDataSource.SelectCommand = "select " + "RecruiterID,Email,CompanyName, " + "ContactName,Address,Activate from tblRCAccounts"; gridView.DataSource = sqlDataSource; gridView.DataBind(); } }

Phn thit k giao din trang:

Lu hnh ni b

Trang 285

Trong ct u tin [Email] c chn dng HyperLinkField :

Kt qu thc thi:

Lu hnh ni b

Trang 286

9.1.7.3 To ct ButtonField To trang ASP.NET GridViewAndButtonPage.aspx s dng GridView c ct loi ButtonField. Phn m lnh thit k trang GridViewAndButtonPage.aspx :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewAndButtonPage.aspx.cs" Inherits="GridViewAndButtonPage" %> <!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 runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDeleting="GridView1_RowDeleting"> <Columns> <asp:HyperLinkField DataNavigateUrlFields="RecruiterID" DataNavigateUrlFormatString="~/Details.aspx?RecruiterID={0}" DataTextField="Email" HeaderText="Email"> <HeaderStyle HorizontalAlign="Left" /> </asp:HyperLinkField> <asp:BoundField DataField="CompanyName" HeaderText="Ten Cong Ty"> <HeaderStyle HorizontalAlign="Left" /> </asp:BoundField> <asp:BoundField DataField="ContactName" HeaderText="Lien He"> <HeaderStyle HorizontalAlign="Left" /> </asp:BoundField> <asp:ButtonField ButtonType="Button" Text="Delete" CommandName="Delete" />

Lu hnh ni b

Trang 287

</Columns> </asp:GridView> </div> </form> </body> </html>

Phn giao din thit k trang GridViewAndButtonPage.aspx:

Phn m lnh thc thi trang GridViewAndButtonPage.aspx.cs :


public partial class GridViewAndButtonPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { FillData(GridView1); } void FillData(GridView gridView) { SqlDataSource sqlDataSource = new SqlDataSource(); sqlDataSource.ConnectionString = WebConfigurationManager.ConnectionStrings[ "RecruitVietnamDbConnectionString" ].ConnectionString; sqlDataSource.SelectCommandType = SqlDataSourceCommandType.Text; sqlDataSource.SelectCommand = "select " + "RecruiterID,Email,CompanyName, " + "ContactName,Address,Activate from tblRCAccounts"; gridView.DataSource = sqlDataSource; gridView.DataBind(); }

Lu hnh ni b

Trang 288

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { Response.Write(e.RowIndex.ToString()); }

Kt qu thc thi : Khi click nt Delete ti mt dng no trn GridView s gy ra s kin OnRowDeleting="GridView1_RowDeleting v gi phng thc sau:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { Response.Write(e.RowIndex.ToString()); }

Xa mu tin u khi click nt Delete ti dng u tin trn GridView. Kt qu nh sau:

9.1.7.4 To ct ImageField Tng t nh ct HyperLink, GridView cng c mt ct chuyn hin th hnh nh (ImageField) nu trng d liu gn vi n cha ng dn n nh nm trong ng dng. to ct cho php hin th Image, dng th <asp:ImageField DataImageUrlField ../> 9.1.8 To v x l cc ct Select, Edit, Delete, Update Ch : thc hin vic thm cc nt [Select] [Edit] [Delete] trong GridView, khi to iu khin d liu SqlDataSource phi chn mc Advanced

Lu hnh ni b

Trang 289

v click chn mc [X] Generate INSERT, UPDATE and DELETE statements. Click OK xc nhn.

Phn m lnh ca iu khin SqlDataSource s c thm phn khai bo sau:


<asp:SqlDataSource id="sourceProducts" runat="server" SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products]" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"

Lu hnh ni b

Trang 290

UpdateCommand="UPDATE [Products] SET [ProductName] = @ProductName, [UnitPrice] = @UnitPrice WHERE [ProductID] = @original_ProductID AND [ProductName] = @original_ProductName AND (([UnitPrice] = @original_UnitPrice) OR ([UnitPrice] IS NULL AND @original_UnitPrice IS NULL))" ConflictDetection="CompareAllValues" DeleteCommand="DELETE FROM [Products] WHERE [ProductID] = @original_ProductID AND [ProductName] = @original_ProductName AND (([UnitPrice] = @original_UnitPrice) OR ([UnitPrice] IS NULL AND @original_UnitPrice IS NULL))" InsertCommand="INSERT INTO [Products] ([ProductName], [UnitPrice]) VALUES (@ProductName, @UnitPrice)" OldValuesParameterFormatString="original_{0}" > <DeleteParameters> <asp:Parameter Name="original_ProductID" Type="Int32" /> <asp:Parameter Name="original_ProductName" Type="String" /> <asp:Parameter Name="original_UnitPrice" Type="Decimal" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> <asp:Parameter Name="original_ProductID" Type="Int32" /> <asp:Parameter Name="original_ProductName" Type="String" /> <asp:Parameter Name="original_UnitPrice" Type="Decimal" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> </InsertParameters> </asp:SqlDataSource>

9.1.8.1 Thm ct Select, Edit - Update, Delete GridView khng ch hin th c cc bng d liu m cn h tr rt tt trong vic chnh sa v xa d liu. c bit khi ngun d liu l SqlDataSource th vic sa v xa hon ton t ng, khng cn phi vit bt k dng code no. bt tnh nng ny, cn b sung thm thuc tnh vo GridView vi gi tr l true cho AutoGenerateSelectColum, AutoGenerateEditColum, AutoGenerateDeleteColum. Th d: To trang ASP.NET s dng GridView c ct Select. Thit k giao din trang GridViewSelect.aspx c ct Select <asp:CommandField
ShowSelectButton="True" />

Lu hnh ni b

Trang 291

Phn m lnh thit k trang


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewSelect.aspx.cs" Inherits="GridViewSelect" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> Categories:<br /> <asp:SqlDataSource ID="sourceCategories" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT * FROM [Categories]"></asp:SqlDataSource> <asp:GridView ID="gridCategories" runat="server" DataSourceID="sourceCategories" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataKeyNames="CategoryID" AutoGenerateColumns="False" > <Columns> <asp:CommandField ShowSelectButton="True" /> <asp:BoundField DataField="CategoryID" HeaderText="CategoryID"

Lu hnh ni b

Trang 292

InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" /> <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" /> <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" /> </Columns> <RowStyle BackColor="White" ForeColor="#330099" /> <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" /> <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" /> </asp:GridView> <br /> Products in this category:<br /> <asp:SqlDataSource ID="sourceProducts" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT ProductID, ProductName, UnitPrice FROM Products WHERE (CategoryID = @CategoryID)"> <SelectParameters> <asp:ControlParameter Name="CategoryID" ControlID="gridCategories" PropertyName="SelectedDataKey.Value" DefaultValue="1" /> </SelectParameters> </asp:SqlDataSource> <asp:GridView ID="gridProducts" runat="server" DataSourceID="sourceProducts" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" AutoGenerateColumns="False" DataKeyNames="ProductID" > <RowStyle BackColor="White" ForeColor="#330099" /> <Columns> <asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False" ReadOnly="True" SortExpression="ProductID" /> <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" /> <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" /> </Columns> <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" /> <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" /> </asp:GridView> </div> </form> </body> </html>

Phn m lnh thc thi trang GridViewSelect.aspx.cs :


public partial class GridViewSelect : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) } { }

Kt qu thc hin: Khi click nt [Select] ti mt dng trn GridView, da theo m CategoryID s lc d liu ca GridView di cc Product c CategoryID ny.

Lu hnh ni b

Trang 293

9.1.8.2 Cp nht d liu To trang ASP.NET s dng GridView c ct Edit vi th khai bo sau trong GridView
<asp:CommandField ShowEditButton="True" /> Thit k giao din trang GridViewEdit.aspx :

Phn m lnh thit k trang GridViewEdit.aspx :


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewEdit.aspx.cs" Inherits="GridViewEdit" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title>

Lu hnh ni b

Trang 294

<link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView2" runat="server" DataSourceID="sourceProducts" AutoGenerateColumns="False" DataKeyNames="ProductID"> <Columns> <asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" InsertVisible="False" SortExpression="ProductID" /> <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName"/> <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" /> <asp:CommandField ShowEditButton="True" /> </Columns> </asp:GridView> <asp:SqlDataSource id="sourceProducts" runat="server" SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products]" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" UpdateCommand="UPDATE [Products] SET [ProductName] = @ProductName, [UnitPrice] = @UnitPrice WHERE [ProductID] = @original_ProductID AND [ProductName] = @original_ProductName AND (([UnitPrice] = @original_UnitPrice) OR ([UnitPrice] IS NULL AND @original_UnitPrice IS NULL))" ConflictDetection="CompareAllValues" DeleteCommand="DELETE FROM [Products] WHERE [ProductID] = @original_ProductID AND [ProductName] = @original_ProductName AND (([UnitPrice] = @original_UnitPrice) OR ([UnitPrice] IS NULL AND @original_UnitPrice IS NULL))" InsertCommand="INSERT INTO [Products] ([ProductName], [UnitPrice]) VALUES (@ProductName, @UnitPrice)" OldValuesParameterFormatString="original_{0}" > <DeleteParameters> <asp:Parameter Name="original_ProductID" Type="Int32" /> <asp:Parameter Name="original_ProductName" Type="String" /> <asp:Parameter Name="original_UnitPrice" Type="Decimal" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> <asp:Parameter Name="original_ProductID" Type="Int32" /> <asp:Parameter Name="original_ProductName" Type="String" /> <asp:Parameter Name="original_UnitPrice" Type="Decimal" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> </InsertParameters> </asp:SqlDataSource> </div> </form> </body> </html> Phn m lnh thc thi trang GridViewEdit.aspx.cs :

Lu hnh ni b

Trang 295

public partial class GridViewEdit : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) }

Kt qu thc thi : Click nt [Edit] trn mt dng ca GridView, s cho php bn cp nht thng tin cca1c vng thuc tnh (ngoi tr thuc tnh kha). Click [Update] cp nht, [Cancel] hy thao tc.

9.1.8.3 Xa d liu Quay li th d trn v thit k li giao din trang , click smart tag v click chn mc [x]Enable Deleting. Xut hin thm nt [Delete]

Phn m lnh thit k trang GridViewEdit.aspx :


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewEdit.aspx.cs" Inherits="GridViewEdit" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" />

Lu hnh ni b

Trang 296

</head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView2" runat="server" DataSourceID="sourceProducts" AutoGenerateColumns="False" DataKeyNames="ProductID"> <Columns> <asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" InsertVisible="False" SortExpression="ProductID" /> <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName"/> <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" /> <asp:CommandField ShowEditButton="True" ShowDeleteButton="True" /> </Columns> </asp:GridView> <asp:SqlDataSource id="sourceProducts" runat="server" SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products]" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" UpdateCommand="UPDATE [Products] SET [ProductName] = @ProductName, [UnitPrice] = @UnitPrice WHERE [ProductID] = @original_ProductID AND [ProductName] = @original_ProductName AND (([UnitPrice] = @original_UnitPrice) OR ([UnitPrice] IS NULL AND @original_UnitPrice IS NULL))" ConflictDetection="CompareAllValues" DeleteCommand="DELETE FROM [Products] WHERE [ProductID] = @original_ProductID AND [ProductName] = @original_ProductName AND (([UnitPrice] = @original_UnitPrice) OR ([UnitPrice] IS NULL AND @original_UnitPrice IS NULL))" InsertCommand="INSERT INTO [Products] ([ProductName], [UnitPrice]) VALUES (@ProductName, @UnitPrice)" OldValuesParameterFormatString="original_{0}" > <DeleteParameters> <asp:Parameter Name="original_ProductID" Type="Int32" /> <asp:Parameter Name="original_ProductName" Type="String" /> <asp:Parameter Name="original_UnitPrice" Type="Decimal" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> <asp:Parameter Name="original_ProductID" Type="Int32" /> <asp:Parameter Name="original_ProductName" Type="String" /> <asp:Parameter Name="original_UnitPrice" Type="Decimal" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> </InsertParameters> </asp:SqlDataSource> </div> </form> </body> </html>

Phn m lnh thc thi trang Lu hnh ni b Trang 297

public partial class GridViewEdit : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } }

Kt qu thc thi

Click nt [Delete] ti mt dng trn GridView, mu tin ti dng s b xa. 9.2 i tng d liu DetailsView Dng trnh by d liu l mt mu tin ti mt thi im. Chng ta s xem th d di y qua nm vng cch s dng i tng ny. Th d : Thit k giao din trang DetailsViewTest.aspx :

Phn m lnh thit k trang DetailsViewTest.aspx :


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DetailsViewTest.aspx.cs" Inherits="DetailsView" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:DetailsView ID="DetailsView1" runat="server" AllowPaging="True" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" Height="50px"

Lu hnh ni b

Trang 298

Width="336px" AutoGenerateRows="False" DataKeyNames="ProductID" AutoGenerateEditButton="True" AutoGenerateInsertButton="True" AutoGenerateDeleteButton="true" OnDataBound="DetailsView1_DataBound"> <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <CommandRowStyle BackColor="#FFFFC0" Font-Bold="True" /> <RowStyle BackColor="#FFFBD6" ForeColor="#333333" /> <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" /> <FieldHeaderStyle BackColor="#FFFF99" Font-Bold="True" /> <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> <Fields> <asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False" ReadOnly="True" SortExpression="ProductID" /> <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" /> <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" /> </Fields> </asp:DetailsView> </div> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>" SelectCommand="SELECT ProductID, ProductName, UnitPrice FROM Products" UpdateCommand="UPDATE Products SET ProductName=@ProductName, UnitPrice=@UnitPrice WHERE ProductID=@ProductID" InsertCommand="INSERT Products (ProductName, UnitPrice) VALUES (@ProductName, @UnitPrice)" DeleteCommand="DELETE Products WHERE ProductID=@ProductID" OnInserted="SqlDataSource1_Inserted" ></asp:SqlDataSource> </form> </body> </html>

Cc thuc tnh quan trong trong th <asp:DetailsView>:


AutoGenerateEditButton="True" // nt [Edit] AutoGenerateInsertButton="True" // nt [New] AutoGenerateDeleteButton="true" // nt [Delete]

S kin ca th <asp:DetailsView> :
OnDataBound="DetailsView1_DataBound" protected void DetailsView1_DataBound(object sender, EventArgs e) { if (insertComplete) { // Show the last record (the newly added one). DetailsView1.PageIndex = DetailsView1.PageCount - 1; } }

Lu hnh ni b

Trang 299

Phn m lnh thc thi trang DetailsViewTest.aspx.cs :


public partial class DetailsView : System.Web.UI.Page { private bool insertComplete = false; protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e) { // Flag that a new record is inserted, which we'll show when the grid is bound. if (e.AffectedRows > 0) insertComplete = true; // You could also get output parameters at this point from e.Command. // For example, if you called a stored procedure that returns the newly // generated ProductID value, you could get it here. } protected void DetailsView1_DataBound(object sender, EventArgs e) { if (insertComplete) { // Show the last record (the newly added one). DetailsView1.PageIndex = DetailsView1.PageCount - 1; } } }

Kt qu thc thi :

Click nt [Edit], sau click [] cp nht hoc [] hy

Click nt [New], nhp thng tin sau click nt [Insert] chn mu tin mi hoc [Cancel] hy thao tc.

Lu hnh ni b

Trang 300

9.3 i tng d liu FormView Dng trnh by d liu l mt mu tin ti mt thi im. Tng t nh DetailsView nhng cho php trnh by d liu theo cc mu ty chn (custom temnplates). Chng ta s xem th d di y qua nm vng cch s dng i tng ny. Th d : Thit k giao din trang

Phn m lnh thit k trang FormViewTest.aspx :


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FormViewTest.aspx.cs" Inherits="FormView" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:SqlDataSource ID="sourceProducts" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>" SelectCommand="SELECT * FROM Products"></asp:SqlDataSource> <asp:DropDownList ID="lstProducts" runat="server" AutoPostBack="True" DataSourceID="sourceProducts" DataTextField="ProductName" DataValueField="ProductID" Width="184px">

Lu hnh ni b

Trang 301

</asp:DropDownList> <br /> <br /> <asp:SqlDataSource ID="sourceProductFull" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>" SelectCommand="SELECT * FROM Products WHERE ProductID=@ProductID"> <SelectParameters> <asp:ControlParameter Name="ProductID" ControlID="lstProducts" PropertyName="SelectedValue" /> </SelectParameters> </asp:SqlDataSource> <asp:FormView ID="FormView1" runat="server" DataSourceID="sourceProductFull" Width="184px" BackColor="#FFE0C0" BorderStyle="Solid" BorderWidth="2px" CellPadding="5"> <ItemTemplate> <b>In Stock:</b> <%# Eval("UnitsInStock") %> <br /> <b>On Order:</b> <%# Eval("UnitsOnOrder") %> <br /> <b>Reorder:</b> <%# Eval("ReorderLevel") %> <br /> <br /> </ItemTemplate> </asp:FormView> </div> </form> </body> </html>

thit k mu ty chn (custom templates), chn mc Edit Templates trong FormView Taks :

Nhp ni dung nh hnh di vo trong khung Item Template

Lu hnh ni b

Trang 302

Trong FormView s c mu ty chn (custom template) nh sau , nhp vo cc kt ni d liu ly gi tr cc vng trong bng Products ca CSDL Northwind:
<ItemTemplate> <b>In Stock:</b> <%# Eval("UnitsInStock") %> <br /> <b>On Order:</b> <%# Eval("UnitsOnOrder") %> <br /> <b>Reorder:</b> <%# Eval("ReorderLevel") %> <br /> <br /> </ItemTemplate>

Click nt [End Template Editing] kt thc vic to cc custom templates. Phn m lnh thc thi trang FormViewTest.aspx :
public partial class FormView : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } }

Kt qu thc thi FormViewTest.aspx.cs :

Click chn mt gi tr trong DropdownList, ni dung ca FormView s thay i theo tng ng. 9.4 i tng d liu DataList Dng trnh by d liu l mt mu tin ti mt thi im. Chng ta s xem th d di y qua nm vng cch s dng i tng ny. Th d : Thit k giao din trang Lu hnh ni b Trang 303

Phn m lnh thit k trang DataListAndDropDownList.aspx :


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataListAndDropDownList.aspx.cs" Inherits="DataListAndDropDownList" %> <!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 runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <div> <table width="50%"> <tr> <td style="width: 432px; height: 24px"> Country: <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="ProvinceName" DataValueField="ProvinceID" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" Width="189px"> </asp:DropDownList><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RecruitVietnamDbConnectionString %>" SelectCommand="SELECT [ProvinceID], [ProvinceName] FROM [tblProvinces]"></asp:SqlDataSource> </td>

Lu hnh ni b

Trang 304

</tr> <tr> <td style="width: 432px"> <asp:DataList ID="DataList1" runat="server" RepeatColumns="2" RepeatDirection="Horizontal" Width="622px"> <ItemTemplate> <asp:Label ID="Label2" runat="server" Font-Bold="True" Text='<%# Bind("CompanyName") %>' Width="220px"></asp:Label><br /> <asp:Label ID="Label1" runat="server" Text='<%# Bind("Email") %>' Width="220px"></asp:Label> <br /> <asp:Label ID="Label3" runat="server" Text='<%# Bind("Address") %>' Width="220px"></asp:Label><br /> <asp:Label ID="Label4" runat="server" Text='<%# Bind("Phone") %>' Width="220px"></asp:Label><br /> <br /> </ItemTemplate> </asp:DataList></td> </tr> </table> &nbsp; </div> </div> </form> </body> </html>

Trong DataList trn c to custom template

Ni dung trong DataList c th < ItemTemplate > cha ni dung thit k trn.
<ItemTemplate> <asp:Label ID="Label2" runat="server" Font-Bold="True" Text='<%# Bind("CompanyName") %>' Width="220px"></asp:Label><br /> <asp:Label ID="Label1" runat="server" Text='<%# Bind("Email") %>' Width="220px"></asp:Label> <br /> <asp:Label ID="Label3" runat="server" Text='<%# Bind("Address") %>' Width="220px"></asp:Label><br /> <asp:Label ID="Label4" runat="server" Text='<%# Bind("Phone") %>' Width="220px"></asp:Label><br /> <br />

Lu hnh ni b

Trang 305

</ItemTemplate>

Phn m lnh thc thi trang DataListAndDropDownList.aspx :


public partial class DataListAndDropDownList : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) FillRecruiterAccount(this.DataList1,"1"); } void FillRecruiterAccount(DataList DataList1, string Province) { try { SqlDataSource sqlDataSource = new SqlDataSource(); sqlDataSource.ConnectionString = WebConfigurationManager.ConnectionStrings[ "RecruitVietnamDbConnectionString" ].ConnectionString; sqlDataSource.SelectCommandType = SqlDataSourceCommandType.Text; sqlDataSource.SelectCommand = "select " + "RecruiterID, Email,CompanyName," + "ContactName, Address,Phone" + " from tblRCAccounts where " +" ProvinceID='" + Province +"'"; DataList1.DataKeyField= "RecruiterID"; DataList1.DataSource = sqlDataSource; DataList1.DataBind(); } catch (Exception ex) { Response.Write(ex.Message); } } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { FillRecruiterAccount(this.DataList1, DropDownList1.SelectedValue); } }

Kt qu thc thi : u tin ta c mn hnh thc thi sau :

Lu hnh ni b

Trang 306

Sauk hi lc chn gi tr [Country : Thua Thien Hue] trong DropdownList, ta c danh sch mi hin trong DataList gm cc vng ni dung nh trong phn kt ni d liu trong th <ItemTemplate>

9.5 i tng d liu Repeater Dng trnh by d liu l mt mu tin ti mt thi im. Chng ta s xem th d di y qua nm vng cch s dng i tng ny. Th d: Thit k giao din trang

Phn m lnh thit k trang


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RepeaterPage.aspx.cs" Inherits="RepeaterPage" %> <!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 runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RecruitVietnamDbConnectionString %>" SelectCommand="SELECT [RecruiterID], [Email], [CompanyName], [ContactName], [Address], [Phone] FROM [tblRCAccounts]"> </asp:SqlDataSource> </div>

Lu hnh ni b

Trang 307

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" DataMember="DefaultView"> <HeaderTemplate> <table border="1"> <tr> <td><b>Email</b></td> <td><b>CompanyName</b></td> <td><b>Address</b></td> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td> <%# DataBinder.Eval(Container.DataItem, "Email") %> </td> <td><asp:Label runat="server" ID="Label1" Text='<%# Bind("CompanyName") %>' /> </td> <td> <asp:Label runat="server" ID="Label3" Text='<%# Eval("Address") %>' /></td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> &nbsp; </form> </body> </html>

Phn m lnh thc thi trang


public partial class RepeaterPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) }

Kt qu thc thi :

Lu hnh ni b

Trang 308

BI THC HNH CHNG 9: Bi 1: Thc hnh li cc th d trong bi hc n li ni dung va hc. Bi 2: Thit k giao din trang RecordEditorDataSource.aspx :

Cu hnh SqlDataSource vi chui kt ni :


<add name="NorthwindConnectionString" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI" providerName="System.Data.SqlClient" />

Phn m lnh thit k trang RecordEditorDataSource.aspx :


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RecordEditorDataSource.aspx.cs" Inherits="RecordEditorDataSource" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Record Editor</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList ID="lstProduct" runat="server" AutoPostBack="True" Width="280px" DataSourceID="sourceProducts" DataTextField="ProductName" DataValueField="ProductID"> </asp:DropDownList> <br /> <br /> <hr />

Lu hnh ni b

Trang 309

<br /> <table> <tr> <td style="width: 234px" valign="top"> <asp:DetailsView ID="DetailsView1" runat="server" DataSourceID="sourceProductDetails" Height="50px" Width="200px" AutoGenerateEditButton="True" AutoGenerateRows="False" DataKeyNames="ProductID"> <Fields> <asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False" ReadOnly="True" SortExpression="ProductID" /> <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" /> <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" /> <asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" /> <asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder" SortExpression="UnitsOnOrder" /> <asp:BoundField DataField="ReorderLevel" HeaderText="ReorderLevel" SortExpression="ReorderLevel" /> <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" SortExpression="Discontinued" /> </Fields> </asp:DetailsView> &nbsp; </td> <td style="width: 190px"> <br /> <br /> </td> </tr> </table> <asp:SqlDataSource ID="sourceProducts" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [ProductName], [ProductID] FROM [Products]" /> <asp:SqlDataSource ID="sourceProductDetails" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT ProductID, ProductName, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued FROM Products WHERE ProductID=@ProductID" UpdateCommand="UPDATE Products SET ProductName=@ProductName, UnitPrice=CONVERT(money, @UnitPrice), UnitsInStock=@UnitsInStock, UnitsOnOrder=@UnitsOnOrder, ReorderLevel=@ReorderLevel, Discontinued=@Discontinued WHERE ProductID=@ProductID"> <SelectParameters> <asp:ControlParameter ControlID="lstProduct" Name="ProductID" PropertyName="SelectedValue" /> </SelectParameters> <UpdateParameters> <asp:Parameter Name="ProductName" />

Lu hnh ni b

Trang 310

<asp:Parameter Name="UnitPrice" /> <asp:Parameter Name="UnitsInStock" /> <asp:Parameter Name="UnitsOnOrder" /> <asp:Parameter Name="ReorderLevel" /> <asp:Parameter Name="Discontinued" /> <asp:Parameter Name="ProductID" /> </UpdateParameters> </asp:SqlDataSource> <asp:Label ID="lblInfo" runat="server" EnableViewState="False" Font-Bold="True" ForeColor="#C00000"></asp:Label> <br /> <br /> <br /> <hr /> This page allows overlapping edits. See RecordEditorDataSource_MatchAllValues.aspx for a version that doesn't. </div> </form> </body> </html> Phn m lnh thc thi trang RecordEditorDataSource.aspx.cs : public partial class RecordEditorDataSource : System.Web.UI.Page { }

Kt qu thc thi :

Chn ProductName trong DropdownList, ni dung DetailsView s c cp nht ngay.

Lu hnh ni b

Trang 311

Chng 10:

Bo Mt ng Dng Web

Kt thc chng ny cc bn c th : Trnh by c cc loi bo mt trong ASP.Net M t c Form-Base Authentication Thc thi c bo mt s dng Form-Base Authentication 10.1 Gii Thiu v Bo Mt Trong ASP.Net Bo mt rt quan trng cho vic pht trin v bo tr cc ng dng Web. Mi WebSite c cc thit lp bo mt khc nhau. C ba tnh nng bo mt c bn cho cc ng dng ASP.Net :

Hnh 10.1 Ba tnh nng bo mt cho cc ng dng ASP.NET Authentication : c dng xc nhn nh dannh ngi dng trc khi cho php hoc t chi cc yu cu . Th d : trong ng dng e-mail , tn ngi dng v mt khu phi ph hp khi so snh cc thng ny trong c s d liu. Authorization : ch nhng ngi dng c s nh danh hp l mi c th truy cp n cc ti nguyn c ch nh trong ng dng. Th d : sinh vin khng th truy cp c thng tin thi, im thi m ch c gio vin hoc ngi qun tr mi c th truy cp. Impersionation : ng dng ASP.Net x l cc hot ng i din cho ngi dng m c xc nhn bng IIS ( Internet Information Services ) . IIS truyn du hiu xc nhn n ng dng ASP.Net. Sau ng dng ASP.Net s dng du hiu ny v hot ng di s nh danh ca ngi dng xc nhn. Form-Based Authentication S dng Forms Authentication Provider . Trong forms-base authentication nh dng HTML thng s dng tp hp cc thng tin xc nhn : tn ng nhp , mt khu. ng dng phi vit cc lnh xc nhn cc thng tin c cung cp phi ph hp trong c s d liu. Nhng thng tin c xc nhn ca ngi dng c th c lu trong mt bin cookie trong sut phin lm vic.

Lu hnh ni b

Trang 312

Passport Authentication Ngi dng c xc nhn bng cc s dng Passport Service c cung cp bi Microsoft . Tuy nhin , khi s dng loi xc nhn ny, chng ta phi c ng k vi Microsofts Passport Service. Passport server s dng c ch m ha cookie nh danh v xc nhn tnh hp l ca ngi dng.

Windows Authentication Windows authentication l cch xc nhn mc nh ca ASP.Net. Loi xc nhn ny da vo cc windows account ca ngi dng. Windows authentication trong ASP.Net s dng II c th cu hnh cho php ch cc ngi dng trong Windows domain ng nhp vo ng dng.

C 4 ty chn c thit lp trn IIS : Anonymous Authentication : cho php bt k ngi dng truy cp n ng dng ASP.Net Basic Authentication : yu cu s dng tn ngi dng v mt khu ca Windows kt ni n ng dng. Tuy nhin mt khu c truyn trong dng text n gin , do loi xc nhn ny khng c an ton . Digest Authentication : tng t nh Basic Authentication. Tuy nhin mt khu c hashed sau mi c truyn i ( gia tng s an ton ). Integrated Windows Authentication : s dng Kerberos hoc giao thc change/response xc nhn ngi dng. 10.2 Th d minh ha Th d : minh ha s dng Form-based Authentication trong ng dng Web theo yu cu : ngi dng truy cp vo cc trang trong th mc Admin bt buc phi ng nhp , nu khng ng nhp ngi dng ch c xem danh sch cc loi mt hng bng cch truy cp vo trang DanhSachLoaiMatHang.aspx

Lu hnh ni b

Trang 313

Bc 1 : Xy dng 1 ng dng Web gm cc trang ASP.Net : CapNhatLoaiMatHang.aspx, DanhSachLoaiMatHang.aspx, DangNhap.aspx. Cc trang Web ny c cu trc ng dng web nh hnh sau :

Hnh 10.2Giao din trang DangNhap.aspx

Hnh 10.3 Giao din trang CapNhatLoaiMatHang.aspx Bc 2 : Cu hnh phn <authentication>....</authentication> trong tp tin Web.config nh sau :

Lu hnh ni b

Trang 314

loginUrl : ch r trang ngi dng s ng nhp defaultUrl : ch r trang s c chuyn n nu ng nhp thnh cng. name : ch r tn Cookie s c to timeout : thi gian cookie s tn ti (tnh bng pht ) passwordFormat : khng m ha mt khu ( password) Trong th d ny chng ta khai bo 2 ngi dng (user ) c tn ng nhp l tom v jerry , cc bn c th lu cc user ny trong c s d liu kim tra khi ng nhp Bc 3 . Trn ca s Server Explorer , chn th mc Admin , t menu ng cnh ca th mc chn Add | New Item . Ca s Add New Item xut hin thm vo 1 tp tin Web.config kim tra vic truy cp cho th mc ny.

Ni dung ca tp tin Web.config trong th mc Admin: Lu hnh ni b Trang 315

Bc 4 . Vit lnh x l cc s kin cho cc trang . Trang DangNhap.aspx , cc bn vit lnh cho nt DangNhap nh hnh sau :

Hnh 10.4 Phn m lnh trang DangNhap.aspx Trang CapNhatLoaiMatHang.aspx , cc bn vit thm vo s hin Page_Load v s kin cho link button ng Xut nh hnh sau :

Lu hnh ni b

Trang 316

Hnh 10.5 Phn m lnh trang CapNhatLoaiMatHang.aspx Bc 5. Trong ca s Solution Explorer , chn trang CapNhatLoaiMatHang.aspx nhn phi chut | View in Brower thi hnh trang web.Khi ngi dng truy cp vo trang ny m cha ng nhn th ASP.Net t ng chuyn qua trang DangNhap.aspx Kt qu s xut hin nh sau.

Lu hnh ni b

Trang 317

Hnh 10.6 Mn hnh hin th trang DangNhap.aspx Nhp vo Tn ng nhp : tom v Mt khu l tom sau nhn nt ng nhp vo trang CapNhatLoaiMatHang.aspx.Nu ngi dng chn Nh thng tin ny..... th trong vng 30 pht c th truy cp vo trang CapNhatLoaiMatHang.aspx m khng cn phi ng nhp .

Hnh 10.7 Trang cp nhp thng tin mt hng Sau khi ngi dng cp nht thng tin loi mt hng , sau nhp vo ng xut tr v trang DangNhap.aspx khi tt c cc thng tin session hay cookie u c hy kt thc mt phin lm vic.

Lu hnh ni b

Trang 318

Chng 11:

GII THIU AJAX

Kt thc chng ny cc bn c th : Trnh by c k thut lp trnh ASP.Net & Ajax . M t v xy dng c ng dng Ajax ASP.Net vi XMLHttpRequest. M t v xy dng c ng dng Ajax ASP.Net vi ASPCallBack . M t v xy dng c ng dng Ajax ASP.Net vi Ajax Controls : ScriptManager Control, UpdatePanel Control, Timer Controls M t v xy dng c ng dng Ajax ASP.Net vi Ajax Controls Toolkits.

11.1 Gii thiu AJAX AJAX l mt cng ngh cho php lp trnh bt ng b trong ng dng Web. Thng thng ngi dng mun thay i thng tin t trang Web bng cch nhp vo cc nt lnh(button) hay cc lin kt (link) submit yu cu v Web Server thay i ni dung trang Web (postback). Nh vy ton b trang Web phi c x l li do tn kh nhiu thi gian v gia tng s phn hi cc trang Web,.. Cng ngh Ajax ( Asynchronous JavaScript and XML) cho php ch cc thng tin no cn thay i c gi v Sever x l , sau Server s x l v tr kt qu v cho Client. Sau y l mt vi thng tin chung s gip chng ta hiu hn v Ajax : AJAX bt u ph bin t nm 2005 bi Google (vi mt ng dng Google Suggest, Google Maps, Gmail) . AJAX khng phi l ngn ng lp trnh mi, m n l mt cng ngh mi to ra mt ng dng web nh hn, nhanh hn, tt hn v giao din thn thin vi ngi dng hn. Ajax da trn cc thnh phn HTML trc y : HTML CSS JavaScript (ch cht) XML AJAX l mt cng ngh c h tr bi trnh duyt (browser) v n c lp vi cc ng dng Web server. Vi Ajax, Javascript ca bn c th lin lc trc tip vi Web server bng cch s dng i tng XMLHttpRequest ca Javascript. Vi i tng ny Javascript ca bn c th trao i d trc tip Web server m khng cn trnh (submit) ton b d liu n, do trang web ca bn khng reload li . Ajax s dng c ch lm vic bt ng b (Asynchonous), tc l trong khi i tng XMLHttpRequest thc hin gi yu cu n Web server th Web browser vn tip tc x l cc cng vic khc m khng cn Web server hon thnh vic tr li li yu cu . Nhiu cng vic c s l song song vi nhau, iu ny khc vi cch lp trnh web c in trc y, do ng dng web s chy nhanh hn . Ajax l mt k thut ca Web browser v c lp vi Web server Tt c Web c s dng Ajax gi l Web 2.0 Ajax c th gi v nhn d liu vi nhiu nh dng khc nhau, bao gm XML, HTML v thm ch l file text . 11.2 Ajax Lm Vic Nh Th No ? Lu hnh ni b Trang 319

Ta hy phn tch v so snh cch thc hot ng ca mt trang web thng thng v mt trang web c ng dng Ajax thy r cch thc thc hin ca Ajax . Vi cch lp trnh Web trc y ( cn gi l Web 1.0 ) th khi ngi dng cn cp nht thng tin ( click vo mt mt Button no ), th yu cu thay i thng tin s c gi t pha Client v Server di dng HTTP request , ton b trang web s c gi ch khng ring g mt vi thng tin cn thay i (dng ny gi l postback). Lc Client s ri vo trng thi ch (waiting), trong lc ny pha Client khng th thc hin mt cng vic no khc. Khi Server x l hon thnh cc yu cu v th s gi tr li cho pha Client mt trang web khc thay th trang c (thng tin m Server response li dng HTML v CSS). Qui trnh ny c m t nh sau :

Hnh 11.1 Cch thc hot ng trang Web thng thng. Nh vy ta thy cch thc hot ng ca 1 trang web c in l : Click waiting .. refresh .Do cho d yu cu cp nht mt lng thong tin nh th trang web cng phi load li, do cch trang web chy chm . Vi cch lp trnh Web c ng dng k thut Ajax th Ajax cho php to ra mt Ajax Engine nm gia UI (user interface giao din ngi dng) v Server , tc l nm gia giao tip Client Server, nhng phn Ajax Engine ny vn nm pha Client .

Hnh 11.2 Cch thc hot ng trang Web c Ajax. Khi cng vic cng vic gi request v nhn response u do Ajax Engine thc hin. Thay v tr d liu di dng HTML v CSS trc tip cho trnh duyt, Web server c th gi tr d Lu hnh ni b Trang 320

liu dng XML v Ajax Engine s tip nhn, phn tch v chuyn i thnh XHTML + CSS cho trnh duyt hin th. Vic phn tch v chuyn i ny c thc hin trn Client nn gim ti rt nhiu cho Server, ng thi User cm thy kt qu x l c hin th tc th m khng cn np li ton b trang. Mt khc, s kt hp ca cc cng ngh web nh CSS v XHTML lm cho vic trnh by giao din trang web tt hn nhiu v gim ng k dung lng trang phi np. y l nhng li ch ht sc thit thc m Ajax em li. Ajax Engine ch gi i nhng thng tin cn thay i ch khng phi ton b trang web, do gim c ti qua mng . Vic gi request v nhn response do Ajax Engine thc. Do pha Browser UI khng ri vo trng thi ch (waiting), tc l c th thc hin nhiu vic cng lc (Asynchronous). C th nhn vo 2 hnh sau y so snh hai m hnh ng dng Web: truyn thng v s dng Ajax.

Hnh 11.3 Cch thc hot ng trang Web khng/c Ajax. Sau y l cc bc ci t Ajax n gin, cc bc nh sau : Pha Client : o Vit hm to i tng XMLHttpRequest (i tng ny dng gi request n Server). o Vit hm gi yu cu (request) n Server.

Lu hnh ni b

Trang 321

o Vit hm x l thng tin sau khi gi request n Server. C th l thng tin li tr v (nu vic gi request tht bi) hay l thng tin do Server tr li li .. Pha Server : o Vit hm x l cc yu cu (request) t Client gi n. Thc hin Vit hm to i tng XMLHttpRequest. o bt u vit mt ng dng web dng cng ngh Ajax, u tin ta phi khi to i tng XMLHttpRequest, i tng ny c dung gi request n Server v ly response t Server . o Ty trnh duyt m ta c cc cch khi to i tng XMLHttpRequest khc nhau. o C bn ta c 2 loi trnh duyt: Internet Explorer. Mozilla, Firefox, and Netscape Navigator. Khi to i tng XMLHttpRequest i vi Internet Explorer browser: IE dng i tng ActiveXObject khi to. Do , trc ht phi kim tra i tng ActiveXObject c tn ti hay khng, ta thc hin nh sau: if (window.ActiveXObject) // nu true th l IE Ta bt u khi to i tng XMLHttpRequest vi ActiveXObject: XHRObject = new ActiveXObject(Microsoft.XMLHTTP); Khi to i tng XMLHttpRequest i vi cc browser khc: Cc trnh duyt khc dng i tng XMLHttpRequest khi to. Trc tin phi kim tra i tng XMLHttpRequest c tn ti hay khng, ta thc hin nh sau: if (window.XMLHttpRequest) // nu true th khng phi IE Sau khi to i tng XMLHttpRequest: XHRObject = new XMLHttpRequest(); Code y khi to XMLHttpRequest: var XHRObject; function CreateXMLHttpRequest() { if ( window.ActiveXObject ) //nu l IE XHRObject=new ctiveXObject(Microsoft.XMLHTTP); else if ( window.XMLHttpRequest ) //Mozilla, FireFox,. XHRObject = new XMLHttpRequest(); } Vit hm gi yu cu (request) n Server.

Lu hnh ni b

Trang 322

Sau khi ta khi to i tng XMLHttpRequest, ta dng cc phng thc open(), send() v thuc tnh onreadystatechange ca i tng XMLHttpRquest thc hin gi request n Server, ta thc hin theo cc bc sau : M mt request ti server bng hm open(): open(method,URL[,asyncFlag[,userName[,password]]]) o Ch gii: o method: Phng thc HTTP c dng m mt kt ni, Th d GET hoc POST o GET: vi giao thc ny ta c th dng ly d liu t pha Server m khng cn send bt k thng tin no ln Server. Mc khc giao thc ny c mc ch gim thiu giao tip khng cn thit qua mng bng vic cached tt c thng tin tr v t web Server, cho nn nhng ln sau khi cn ly d liu c th s gim thiu vic truyn thng tin qua mng bng cch ly d liu t cached. o POST: Vi giao thc ny ta bt buc phi truyn thng tin t Client ln Server trong khi gi request, Th d nh : id=tn Mc khc khi dng giao thc ny th d liu response t Server s khng c cached, do cho d c request d liu c hay mi th n u phi gi thng tin ca form ln web server v ly d liu mi v. o URL: ng dn URL request n server o asyncFlag: Cch gi l ng b hay bt ng b, nu asyncFlag = true: bt ng b (asynchronous), ngc l l ng b (synchronous). Mc nh asyncFlag = true o userName: Tn ng nhp ti Server (nu server yu cu) o password: Mt khu ti Server (nu server yu cu) Lu : cc tham s trong cp ngoc [ ] l optional, ngha l c th c hoc khng Th d : XHRObject.open(GET,trang2.aspx,true); XHRObject.open(POST,trang2.aspx,true); (ch : GET v POST phi vit bng ch in hoa) Khai bo hm s x l d liu tr v t Server vi thuc tnh onreadystatechange : XHRObject.onreadystatechange = handleStateChanged; Ta c th t handleStateChanged thnh mt tn khc bt k .y l mt con tr s tr ti hm c tn tng ng x l d liu khi Server response li . K n ta thc hin gi request n Server vi phng thc send() : XHRObject.send(null); Nu trong hm open() ta dng method Get, th trong hm send ny ta bt buc phi truyn d liu ln server: Th d: var queryString = id=123&cateID=abc; XHRObject.send(queryString); Nu trong hm open() ta dng method POST, th trong hm send ny ta khng cn phi truyn d liu ln server: Lu hnh ni b Trang 323

XHRObject.send(null); Code hon chnh gi yu cu v Server function CallServer() { CreateXMLHttpRequest(); if(XHRObject) { XHRObject.open(POST, page1.aspx); XHRObject.onreadystatechange = handleStateChanged; XHRObject.send(null); } } Hay function CallServer () { if(XHRObject) { XHRObject.open(GET, page1.aspx); XHRObject.onreadystatechange = handleStateChanged; XHRObject.send(id=123&name=tung); } } Vit hm x l thng tin khi Server response li : Hm ny phi c tn ging nh khai bo trong thuc tnh onreadystatechange trn .u tin l ta kim tra th request c c gi n Server hay cha vi thuc tnh status, nu bng 4 l request c gi n Server . K n ta kim tra xem Server c response li hay cha vi thuc tnh readyState, nu bng 200 tc l Server response li han tt . Th d : function handleStateChanged() { if (XHRObject.status == 200) //status OK if (XHRObject.readyState==4) //complete document.getElementById(myDiv).innerHTML = XHRObject.responseText; } Th d 1 . Minh ha s dng Ajax s dng XMLHttpRequest Bc 1 : To 1 trang LayGioHienHanh.aspx c giao din nh sau :

Bc 2 . To 1 trang XuLyLayGioHienHanh.aspx , trang ny ch x l yu cu cho trang LayGioHienHanh.aspx do trong Th d ny chng ta khng cn thit k giao din ch vit lnh cho phn Code-Behind trong tp tin LayGioHienHanh.aspx.cs Lu hnh ni b Trang 324

Hnh 11.4 Phn m lnh trang LayGioHienHanh.aspx Bc 3. M trang LayGioHienHanh.aspx , trong phn m HTML vit cc lnh javascript nh hnh sau

Lu hnh ni b

Trang 325

Bc 4. Nhn Ctrl+F5 hoc View in Browser trang LayGioHienHanh.aspx v nhn nt Hin th gi hin hnh ly gi hin hnh t Server nhng trang web khng postback .

Hnh 11.5 Kt qu thc thi. 11.3 ASP.Net Ajax & ASP CallBack Trong phn trc , chng ta bit xy dng mt ng dng ASP.Net Ajax thng qua XMLHttpRequest th chng ta phi xy dng 2 trang ASP.Net v vit m javascript rt nhiu . ASP CallBack h tr xy dng ng dng ASP.Net Ajax mt cch n gin hn (ch vit trong 1 trang ASP.Net ) bng k thut CallBack. s dng c ASP Callback trong trang ASP.Net chng ta phi thc thi cc phng thc RaiseCallbackEvent v GetCallbackResult ca giao din (interface) IcallbackEventHandler . Th d 2 . Trang LayGioHienHanh.aspx trong Th d 1 , chng ta vit li theo ASP CallBack nh sau : Bc 1 : Thit k giao din

Bc 2 : Vit m javascript trong phn HTML :

Lu hnh ni b

Trang 326

Bc 3 : Vit lnh cho pha Sever trong tp tin LayGioHienHanh.aspx .cs

Bc 4 .Nhn Ctrl+F5 hoc View in Browser thi hnh . Nhn nt Hin th gi hin hnh kt qu nh hnh sau .

Lu hnh ni b

Trang 327

11.3 ASP.Net Ajax Server Control ASP.Net Ajax server controls bao gm cc m ca server v client tng tc vi nhau x l cc yu cu t client. Khi cc bn thm cc Ajax control vo trong trang ASP.Net n s t ng gi cc script n trnh duyt thc hin cc chc nng Ajax. Chng ta c th cung cp thm cc on m pha client ty bin cc chc nng cho Ajax control.

Ajax control gm cc control sau y : ScriptManager control : Qun l cc script cho cc thnh phn client , partial-page rendering, localization, globalization v scripts ca ngi dng. Control ny c yu cu s dng cho cc controls : UpdatePanel, UpdateProgress v Timer controls. UpdatePanel : cho php cc bn refresh mt phn ca trang ASP.Net thay v refresh ton b trang s dng postback. UpdateProgress : Cung cp thng tin cc trang thi v partial-page update trong UpdatePanel control. Timer : thc hin vic postback trong mt khong thi gian c ch nh. Chng ta c th s dng control ny post ton b trang hoc s dng cng vi Update Panel control thc hin partial-page update (ch mt phn no trn trang ASP.Net c thay i) vi mt khong thi gian ch nh. Th d 3 . Trang LayGioHienHanh.aspx trong Th d 1 v 2 , chng ta vit li theo ASP.Net ajax server control nh sau : Bc 1: Thit k giao din

Lu hnh ni b

Trang 328

Bc 2: Thit lp phn m HTML

Bc 3 : Vit lnh x l s kin

Bc 4 .Nhn Ctrl+F5 hoc View in Browser thi hnh . Nhn nt Hin th gi hin hnh

Lu hnh ni b

Trang 329

kt qu nh hnh sau .

Th d 4 . To trang SuDungTimerControl.aspx trong Th d 1 , 2, 3 chng ta vit li theo ASP.Net ajax server control hin th ng h hin hnh t server s dng Timer Control. Bc 1: Thit k giao din

Lu hnh ni b

Trang 330

Bc 2 . Vit lnh x l s kin

Bc 3 . Nhn Ctrl+F5 hoc View in Browser thi hnh . Cc bn s thy gi hin hnh c cp nht lin tc mi giy 1 ln.

11.5 Gii thiu AJAX CONTROL TOOLKIT Ajax Control Toolkit cha mt tp phong ph cc iu khin m bn c th s dng xy dng cc ng dng ASP.NET Web Forms cho php p ng v tng tc cao vi Ajax. Thc hin theo cc bc di y ti v v bt u s dng Ajax Control Toolkit vi Visual Studio : 11.5.1 Ti Ajax Control Toolkit Bn g a ch sau http://ajaxcontroltoolkit.codeplex.com/ vo trang :

Lu hnh ni b

Trang 331

Nhp vo lin kt Ajax Control Toolkit Sample Site , chuyn sang trang :

V click nt Download , s chuyn n trang :

Lu hnh ni b

Trang 332

Nhp mc Download chuyn tip trang :

Nhp chn Ajax Control Toolkit Binary.NET35.zip ti gi Ajax Control Toolkit 3.5 v my. Sau , bn gii nn vo trong th mc trn a , gi s a F:\ trong th mc sau F:\Downloads\AjaxControlToolkit.Binary.NET35

Lu hnh ni b

Trang 333

bn s thy c gi AjaxControlToolkitSampleSite.zip, y l ton b cc th d i km vi gi Ajax Control Toolkit 3.5 bn c th tm hiu ton b cc Ajax controls qua cc bi tp tng ng. 11.5.2 Thm Ajax Control Toolkit vo trong Visual Studio Toolbox Thc hin theo cc bc sau: 1. Khi ng Visual Studio v to ra mt website ASP.NET mi. M trang Default.aspx trong trnh son tho Visual Studio. 2. M Hp cng c (toolbox) v to ra mt tab bng cch nhn chut phi v chn mc Add Tab. Tn tab mi l Ajax Control Toolkit.

3. Nhp chut phi vo bn di tab mi v chn Choose Items, xut hin hp thoi Choose Toolbox Items , nhp vo nt Browse v duyt n th mc m bn gii nn gi Ajax Control Toolkit. Chn tp tin AjaxControlToolkit.dll v nhp vo nt Open chn cc Ajax Controls a vo v chuyn v li hp thoi Choose Toolbox Items, nhp nt OK hon tt.

Lu hnh ni b

Trang 334

Lu hnh ni b

Trang 335

Lc ny , trong ca s Toolbox , tab Ajax Control Toolkit va mi thm vo c cc Ajax controls trong nh hnh :

11.6 Tm hiu mt s iu khin trong Ajax Control Toolkit 3.5 11.6.1 Accordion Control. Accordion control gip bn nh ngha nhiu lp v trnh by chng tng ci mt.N ging nh l c nhiu CollapsiblePanel controls m ch c mt c th m rng Lu hnh ni b Trang 336

ti mt thi im xc nh.Accordion control cha mt hoc nhiu AccordionPane controls.Mi AccordionPane control c cha phn header v phn content ca n. Accordion control h tr ch AutoSize sau ty bin vi nhiu c trang khc nhau: None:Accordion control m rng v thu hp khng hn ch. Limit:Accordion control m rng v thu hp khng qu gi tr ca thuc tnh Height. Fill:Accordion control b c nh bi gi tr ca thuc tnh Height Accordion cng c th l data-bound , gn d liu vo control,ch ra ngun d liu s dng thuc tnh Datasource hoc DataSourceID,v sau t cc gi d liu vo thuc tnh HeaderTemplate v ContentTemplate.Bn phi gi phng thc DataBind gn d liu vo iu khin. Pha server:
<ajaxToolkit:Accordion ID="MyAccordion" runat="Server" SelectedIndex="0" HeaderCssClass="accordionHeader" HeaderSelectedCssClass="accordionHeaderSelected" ContentCssClass="accordionContent" AutoSize="None" FadeTransitions="true" TransitionDuration="250" FramesPerSecond="40" RequireOpenedPane="false" SuppressHeaderPostbacks="true"> <Panes> <ajaxToolkit:AccordionPane HeaderCssClass="accordionHeader" HeaderSelectedCssClass="accordionHeaderSelected" ContentCssClass="accordionContent"> <Header> . . . </Header> <Content> . . . </Content> </ajaxToolkit:AccordionPane> . . </Panes> <HeaderTemplate>...</HeaderTemplate> <ContentTemplate>...</ContentTemplate> </ajaxToolkit:Accordion>

Thuc tnh: SelectedIndex i tng AccordionPane c hin th HeaderCssClass Tn ca lp CSS dng cho headers.N c th c p dng cho Accordion control nh l mc nh cho tt c i tng AccordionPane,hoc n c th p dng cho mt i tng Accordion ring Lu hnh ni b Trang 337

HeaderSelectedCssClass Tn ca lp CSS dng cho header c chn. N c th c p dng cho Accordion control nh l mc nh cho tt c i tng AccordionPane, hoc n c th p dng cho mt i tng Accordion ring. ContentCssClass Tn lp CSS dng cho phn ni dung. N c th c p dng cho Accordion control nh l mc nh cho tt c i tng AccordionPane, hoc n c th p dng cho mt i tng Accordion ring. FadeTransitions - true s dng hiu ng chuyn i;ngc li, false. TransitionDuration S giy thc hin hiu ng chuyn i. FramesPerSecond S khung trn mt giy c dng chuyn i hiu ng. AutoSize Gi tr ch ra gii hn ca phn th hin. RequireOpenedPane Gi tr ch ra rng phn ang m s khng ng li khi m header ca n c click, m bo mt pane lun lun m,mc nh l true. SuppressHeaderPostbacks Gi tr ch ra khi m mt phn t bn trong header c gi, n hu ch kh m bn mun t hyperlinks trong header. Panes Tp hp AccordionPane. HeaderTemplate Cc yu t c cha nh du, nn c s dng cho tiu ca mt ca s khi c rng buc d liu. ContentTemplate Phn t cha phn m rng s th hin cho phn ni dung trong khi d liu c gn. DataSource Ngun d liu c s dng. Bn phi gi phng thc Databind iu khin c d liu t ngun d liu. DataSourceID ID ca datasource. DataMember i tng c gn vo khi s dng DataSourceID cho vic gn d liu Phng thc: Tn M t Constructor Constructor mc nh bo cho ASP.NET tr li n nh l th DIV ClearPanes Xa ton b ni dung cc Pane ConnectToDataSourceView Ni iu khin ranh gii d liu ny ti DataSourceView thch hp v mc trnh nghe s kin thch hp (cho) s kin DataSourceViewChanged. Gi tr tr v l th hin mi (nu c) m c ni ti. Mt exception s c nm ra nu c vn trong vic tm kim th hin hoc ngun d liu CreateChildControls To mt AccordionExtender v gn n vo th div s c khi to cho iu khin ny CreateControlHierarchy(System.Boo To ra s phn cp iu khin mi (ca) lean) AccordionPanes (s dng DataSource nu c ch ra) CreateDataSourceSelectArguments To ra DataSourceSelectArguments (vi gi Lu hnh ni b Trang 338

CreateItem(System.Object, System.Int32, AjaxControlToolkit.AccordionItemT ype, AjaxControlToolkit.AccordionConte ntPanel, System.Web.UI.ITemplate, System.Boolean) DataBind DoSelect(System.Collections.IEnum erable) EnsureDataBound FindControl(System.String) GetData

tr mc nh l Empty bi v chng ta ko mun sp xp,lc,..) To mt mc AccordionPane (c Header v Content) v xut hin s kin ItemCreated.

Gn Accordion vi ngun d liu ca n Chn d liu Chc chn rng Accordion gn vi mt ngun d liu nu n bt buc nh th Override FindControl tm control ny,sau kim vo cc phn con ca n Tr v mt Ienumerable ca ngun d liu,c th t thuc tnh DataSource hoc t thuc tnh DataSourceID Gi CommandArgs ca mt s kin ItemCommand vi AccordionCommandEventArgs Gn ni dung vo cc phn ca n Phng thc ny c gi khi DataMember ,DataSource hoc DataSourceID b thay i Bo cho chng ta bit cn phi bao d liu khi DataSourceView b thay i iu khin s kin PreLoad ca trang Bo s kin ItemCommand Bo s kin ItemCreated Bo s kin ItemDatabound Kt ni ti DataSourceView v pht hin nu chng ta vn cn bao d liu OnPreLoad c s dng pht hin chng ta cn cn bao d liu hay ko nh du AccordionPane sao cho n khng b thu gn

OnBubbleEvent(System.Object, System.EventArgs) OnDataBinding(System.EventArgs) OnDataPropertyChanged OnDataSourceViewChanged(System .Object, System.EventArgs) OnInit(System.EventArgs) OnItemCommand(AjaxControlToolk it.AccordionCommandEventArgs) OnItemCreated(AjaxControlToolkit. AccordionItemEventArgs) OnItemDataBound(AjaxControlTool kit.AccordionItemEventArgs) OnLoad(System.EventArgs) OnPagePreLoad(System.Object, System.EventArgs) OnPreRender(System.EventArgs) S kin: Tn ItemCommand Lu hnh ni b

M t S kin xy ra khi lnh c thc thi Trang 339

ItemCreated ItemDataBound Pha Client. Thuc tnh: Tn AutoSize Count FadeTransitions FramesPerSecond

S kin xy ra khi mt mc c to khi bao d liu S kin xy ra khi bao d liu

M t Ch autosize Lm m khi thay i cc pane S lng cc bc trong mt giy trong qu trnh chuyn i.Mc nh l 30 khung hnh trong mt giy Thit lp CSS cho phn header Thit lp CSS cho phn header c chn Ly gi tr index ca Accordion c ch ra,nu khng c th ly gi tr index ca pane ang c chn Thit lp ch bt buc phi c 1pane c m Index ca phn ang c chn

HeaderCssClass HeaderSelectedCssClass Pane

M t To mt th Accordion mi tham chiu n header v ni dung ca n v thm n vo tp hp panes dispose Vt b cc AccordionBehavior initialize Cc chc nng khi to c trch nhim nhn cc ch s c la chn t c ch ClientState v duyt qua tt c cc phn t con sau xy dng mt tp cc phn ,ng cc phn khng c chn,ch trnh by phn c chn hoc mc nh raiseSelectedIndexChanged X l s kin raiseSelectedIndexChanged raiseSelectedIndexChanging X l s kin raiseSelectedIndexChanging S kin: Tn M t selectedIndexChanged Thm mt iu khin s kin cho s kin selectedIndexChanged selectedIndexChanging Thm mt iu khin s kin cho s kin selectedIndexChanging 11.6.2 AlwaysVisible Control. L mt extender c dng hin th mt cch lin tc n mt iu khin ASP.NET.iu khin c m rng s lun lun di chuyn n mt v tr c nh trn trang bt k trang th thay i kch thc hay b cun. Pha Server: Thuc tnh: Lu hnh ni b Trang 340

requireOpenedPane SelectedIndex Phng thc: Tn addPane

Tn HorizontalOffset

HorizontalSide ScrollEffectDuration UseAnimation VerticalOffset VerticalSide Phng thc:

M t Khong cch ti cnh ngang ca trnh duyt tnh bng pixel cng pha vi iu khin ch,mc nh l 0px Pha ca iu khin ph thuc vo,mc nh l bn tri Thi gian tnh bng giy cho hiu ng cun khi iu khin ch thay i v tr,mc inh l 0.1s Cho php hay khng hiu ng mt phn t vo v tr Khong cch ti cnh dc ca trnh duyt tnh bng pixel cng pha vi iu khin ch,mc nh l 0px Pha ca iu khin ph thuc vo,mc nh l bn trn

Tn M t EnsureValid Xc nhn cc tnh hp l Pha Client: Cc hnh vi AlwaysVisibleControl c s dng c nh iu khin lin quan vi mt khong cch ch ra trc tnh t gc trn bn tri d ngi dng c thay i kch thc hay ko thanh cun. Thuc tnh: Tn M t HorizontalOffset Khong cch ti cnh ngang ca trnh duyt tnh bng pixel cng pha vi iu khin ch,mc nh l 0px HorizontalSide Pha ca iu khin ph thuc vo,mc nh l bn tri ScrollEffectDuration Thi gian tnh bng giy cho hiu ng cun khi iu khin ch thay i v tr,mc inh l 0.1s useAnimation Cho php hay khng hiu ng mt phn t vo v tr(vi IE6 gi tr mc nh l true) VerticalOffset Khong cch ti cnh dc ca trnh duyt tnh bng pixel cng pha vi iu khin ch,mc nh l 0px VerticalSide Pha ca iu khin ph thuc vo,mc nh l bn trn Phng thc: Tn M t dispose Hy b cc hnh vi initialize Khi to cc hnh vi raiseRepositioned M t s kin thay i v tr raiseRepositioning M t s kin ti nh v S kin: Lu hnh ni b Trang 341

Tn M t repositioned Thm mt x l s kin cho s kin thay i v tr repositioning Thm mt x l s kin cho s kin ti nh v Th d: <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </asp:ToolkitScriptManager> <asp:Panel ID="Panel1" CssClass="staticPanel" runat="server"> <h2>Hello World!</h2> </asp:Panel> <asp:AlwaysVisibleControlExtender ID="AlwaysVisibleControlExtender1" TargetControlID="Panel1" VerticalSide="Top" VerticalOffset="10" HorizontalSide="Right" HorizontalOffset="10" runat="server" /> 11.6.3 Animation control. Phn m rng c s dng to cc hiu ng cho iu khin khi xy ra s kin. Pha Server: Thuc tnh: Tn M t OnClick Hiu ng tng ng vi hnh ng Click OnHoverOut Hiu ng tng ng vi hnh ng hoverOut OnHoverOver Hiu ng tng ng vi hnh ng HoverOver Onload Hiu ng tng ng vi hnh ng Onload OnMouseOut Hiu ng tng ng vi hnh ng MouseOut OnMouseOver Hiu ng tng ng vi hnh ng MouseOver Phng thc: Tn M t OnPreRender(System.Eve Thay i bt k animationtarget no t ID my ch ntArgs) iu khin sang ClienIDs m m lnh hiu ng hng ti Pha Client Animation l mt lp c s tru tng c dng nh l mt im khi u cho tt c cc hiu ng khc.N cung cp cc c ch c bn cho hiu ng (playing,pausing,stopping,timing,..) v cc hiu ng thc t s hon tt trong cc phng thc tru tng getAnimatedValue v setValue. Thuc tnh: Lu hnh ni b Trang 342

Tn duration Events

fps Id isActive isInitialized isPlaying isUpdating percentComplete target Phng thc: Tn beginUpdate Dispose endUpdate getAnimatedValue Initialize Interpolate

Miu t di thc thi hiu ng,c tnh bng giy,mc nh l 1s Tp hp cc iu khin s kin cho hnh vi,thuc tnh ny ch nn c gi bi cc hnh vi,khng nn gi bi cc m lnh khc S khung hnh trong 1 giy,mc nh l 25 True nu hiu ng ang hot ng,false nu ngc li True nu hiu ng ang chy,false nu ngc li Phn trm hiu ng c chy

Miu t Hy b cc hnh ng Xc nh trng thi ca hiu ng sau mt lng thi gian tri qua

Hm ny c dng xc nh gi tr thch hp gia gi tr bt u v kt thc a ra phn trm hin ti onEnd Phng thc ny ch c gi sau mi ln hiu ng thc thi xong onStart Phng thc ny ch c gi trc mi ln hiu ng thc thi xong onStep Phng thc ny c gi lp li mi bc tin trin ca hiu ng qua mi khung hnh pause Dng hiu ng nu n ang c thc thi,gi play chi tip Play Chy hiu ng hoc chi tip nu pause Play To hiu ng,chy ht v hy nu xong raiseEnded Kch hot s kin ended raisePropertyChang Thay i khai bo s kin ed raiseStarted Kch hot s kin started raiseStep Kch hot s kin step setOwner Lm cho hiu ng ny l con ca hiu ng khc setValue Thit lp trng thi hin ti ca hiu ng Stop Dng chy hiu ng Lu hnh ni b Trang 343

updated S kin: Tn Miu t disposing Ended Thm mt iu khin s kin cho s kin ended propertyChanged Started Thm mt iu khin s kin cho s kin started step Thm mt iu khin s kin cho s kin step Th d: <asp:ToolkitScriptManager ID=ToolkitScriptManager1 runat=server> </asp:ToolkitScriptManager> <asp:Button ID=btn1 runat=server Text=Button OnClientClick=return false;/> <asp:Panel ID=panel1 runat=server CssClass=panel1> ASP.NET AJAX is a free framework for quickly creating a new generation of more efficient, more interactive and highly-personalized Web experiences that work across all the most popular browsers.<br /> </asp:Panel> <asp:AnimationExtender ID=AnimationExtender1 runat=server TargetControlID=btn1> <Animations> <OnClick> <Sequence> <EnableAction enabled=false/> <Sequence AnimationTarget=Panel1> <Resize Width=500 Height=110 Unit=px /> <FadeOut Duration=1.5 Fps=24/> </Sequence> <EnableAction enabled=true/> </Sequence> </OnClick> </Animations></asp:AnimationExtender> Cc hiu ng: Hiu ng: ParentAnimation: o ParallelAnimation. O SequenceAnimation. SelectionAnimation. Lu hnh ni b Trang 344

O ConditionAnimation. O CaseAnimation. FadeAnimation. O FadeInAnimation. O FadeOutAnimation. PulseAnimation. PropertyAnimation. O DiscreteAnimation. O InterpolatedAnimation. ColorAnimation. LengthAnimation. MoveAnimation. ResizeAnimation. ScaleAnimation. Action. EnableAction. HideAction. StyleAction. OpacityAction. ScriptAction. 11.6.4 AsyncFileUpload Control. AsyncFileUpload cho php bn upload file ln server mt cch bt ng b,kt qu ca file upload c th c kim tra c pha server ln client,bn c th lu file c upload bng cch gi phng thc SaveAs() trong iu khin s kin UploadedComplete server. Pha Server. Thuc tnh: Tn M t CompleteBackColor Ly hoc thit lp gi tr mu nn khi file ang c upload,mc nh l Lime ContentType Ly kiu ni dung ca file upload ErrorBackColor Ly hoc thit lp gi tr mu nn khi file upload b li,mc nh l red FileBytes Xc nh dung lng file va upload FileContent To mt i tng Stream tr n file va c upload chun b cho vic c file FileName Xc inh tn file va upload HasFile Tr v gi tr true nu file c upload IsUploading Tr v gi tr true nu file ang c upload OnClientUploadComplete Ly hoc thit lp on m trn client s c thc 345his au khi file c upload OnClientUploadError Ly hoc thit lp on m trn client s c thc thi nu c li xy ra trong khi upload OnClientUploadStarted Ly hoc thit lp on m trn client s c thc Lu hnh ni b Trang 345

PersistedStoreType PostedFile ThrobberID UploaderStyle UploadingBackColor

Width Phng thc: Tn M t Constructor Khi to mt AsyncFileUpload mi ClearAllFilesFromPersistedStore Xa ton b file trong b lu tr ClearFileFromPersistedStore Xa mt tp tin c th trong b lu tr GetBytesFromStream(System.IO.Stream) Nhn mt chui byte t lung file SaveAs(System.String) Lu file upload vi tn c th S kin: Tn M t UploadedComplete S kin xy ra server nu file upload thnh cng UploadedFileError S kin xy ra server nu file upload b li Pha Client( khng c). 11.6.5 AutoComplete Control. Pha Server: Phn m rng cung cp gi hon tt phn nhp vo textbox. Thuc tnh: Tn M t CompletionInterval Thi gian tnh bng ms nhn c gi s dng web service CompletionListCssClass Lp Css c s dng th hin phn ni dung hin ra CompletionListElementID ID ca phn t s l danh sch hon thnh CompletionListHighlightedItem Css Class s c s dng t m mt mc CssClass trong danh sch t ng hon chnh. CompletionListItemCssClass Css Class s c s dng nh dngstyle mt mc trong danh sch t ng hon chnh. CompletionSetCount S lng cc xut c cung cp. ContextKey DelimiterCharacters Xc nh hoc thit lp k t dng phn cch cc t cho autocomplete Lu hnh ni b

thi khi file bt u c upload Xc lp b lu tr iu khin,mc nh l Session Ly mt i tng HttpPostedFile truy xut file va upload Ly hoc thit lp ID ca iu khin c th hin trong khi file ang c upload Xc nh hoc thit lp th hin ca iu khin (Traditional,Modern),mc nh l Traditional Xc nh hoc thit lp mu nn ca iu khin trong khi file ang upload,mc nh l white Xc nh hoc thit lp chiu rng ca iu khin

Trang 346

EnableCaching FirstRowSelected MinimumPrefixLength OnClientHidden OnClientHiding OnClientItemOut OnClientItemOver OnClientItemSelected OnClientPopulated OnClientPopulating OnClientShowing OnClientShown OnHide OnShow ServiceMethod ServicePath

ShowOnlyCurrentWordInComp letionListItem UseContextKey

Cho php b nh m pha client hot ng Xc nh nu dng u tin ca kt qu tm kim c xc nh S lng t nht ca chui k t trc khi webservice a ra gi iu khin gn vo client s kin hidden iu khin gn vo client s kin hidding iu khin gn vo client s kin item out iu khin gn vo client s kin item over iu khin gn vo client s kin item selected iu khin gn vo client s kin populated iu khin gn vo client s kin populating iu khin gn vo client s kin showing iu khin gn vo client s kin shown Hiu ng onhide Hiu ng onshow Phng thc dch v web c gi ng dn n web service m extender s ly t hoc cu,nu khng c cung cp,mc nh l phng thc trang Nu c thit lp l true th phn gi ch cho cc t hin hnh,ngc li th a ra chui cha cc t hin hnh,y l mc nh Cho d thuc tnh ContextKey c c dng hay khng th thuc tnh cng c enable ,nu ContextKey c thit lp th gi tr ny c tham s conextKey cng gi tr kiu string M t To mt i tng JSON th hin text/value c th c tr v bi webservice Chuyn i server IDs thnh client IDs cho hiu ng

Phng thc: Tn CreateAutoCompleteItem(Syste m.String, System.String) OnPreRender(System.EventArgs ) Pha Client Thuc tnh: Tn CompletionInterval completionList CompletionListCssClass CompletionListElementID Lu hnh ni b M t T ng hon thnh tnh bng ms Danh sch phn t dom Lp Css c s dng th hin phn ni dung hin ra ID ca phn t s l danh sch hon thnh Trang 347

CompletionListItemCssClass completionSetCount contextKey delimiterCharacters

Css Class s c s dng nh dngstyle mt mc trong danh sch t ng hon chnh. Kch thc ti a ca completion

Xc nh hoc thit lp k t dng phn cch cc t cho autocomplete EnableCaching Cho php b nh m pha client hot ng FirstRowSelected Xc nh nu dng u tin ca kt qu tm kim c xc nh highlightedItemCssClass Lp css c dng nh dng phn t c t m trong danh sch isMultiWord Ch multi-word minimumPrefixLength S k t t nht web service a ra gi onHide nh ngha JSON ca hiu ng onHide onHideBehavior Hnh vi ca hiu ng onHide onShow nh ngha JSON ca hiu ng onShow onShowBehavior Hnh vi ca hiu ng onShow serviceMethod Phng thc web service servicePath Web service url showOnlyCurrentWordInCompl Nu c thit lp l true th phn gi ch cho etionListItem cc t hin hnh,ngc li th a ra chui cha cc t hin hnh,y l mc nh useContextKey Cho d thuc tnh ContextKey c c dng hay khng th thuc tnh cng c enable ,nu ContextKey c thit lp th gi tr ny c tham s conextKey cng gi tr kiu string Phng thc: Tn dispose hidePopup initialize initializeCompletionList initializeTextBox initializeTimer onHide onShow raiseHidden raiseHiding raiseItemOut raiseItemOver Lu hnh ni b M t X l hnh vi autocomplete Du danh sch hon t ng hon tt Khi to hnh vi autocomplete Khi to danh sch cc phn t autocomplete Khi to textbox Khi to thit b tnh gi Chy hiu ng onHide Chy hiu ng onShow Kch hot s kin hidden Kch hot s kin hiding Kch hot s kin item out Kch hot s kin item over Trang 348

raiseItemSelected raisePopulated raisePopulating raiseShowing raiseShown showPopup S kin: Tn Hidden hiding itemOut itemOver itemSelected Populated Populating Showing shown

Kch hot s kin item selected Kch hot s kin populated Kch hot s kin populating Kch hot s kin showing Kch hot s kin shown Hin danh sch gi

M t Thm iu khin s kin cho s kin Hidden Thm iu khin s kin cho s kin hiding Thm iu khin s kin cho s kin itemOut Thm iu khin s kin cho s kin itemOver Thm iu khin s kin cho s kin itemSelected Thm iu khin s kin cho s kin populated Thm iu khin s kin cho s kin populating Thm iu khin s kin cho s kin showing Thm iu khin s kin cho s kin shown

Th d: <ajaxToolkit:AutoCompleteExtender runat=server ID=autoComplete1 TargetControlID=myTextBox ServiceMethod=GetCompletionList ServicePath=AutoComplete.asmx MinimumPrefixLength=2 CompletionInterval=1000 EnableCaching=true CompletionSetCount=20 CompletionListCssClass=autocomplete_completionListElement CompletionListItemCssClass=autocomplete_listItem CompletionListHighlightedItemCssClass=autocomplete_highlightedListItem DelimiterCharacters=;, : ShowOnlyCurrentWordInCompletionListItem=true> <Animations> <OnShow> </OnShow> <OnHide> </OnHide> </Animations> </ajaxToolkit:AutoCompleteExtender> Lu hnh ni b Trang 349

11.6.6 Calender Control. Pha Server iu khin Calendar extender c th c gn vi bt k iu khin textbox no ca ASP.NET.N cung cp hm nh dng ngy pha client vi nh dng ngy ty bin vi giao din trong mt iu khin popup.Bn c th tng tc vi calendar bng cch click vo mt ngy chn,hoc Today chn ngy hin ti.Ngoi ra,mi tn tri phi c th c s dng chuyn ti thng trc hoc thng sau.Bng cch click vo tiu ca calendar bn c th thay i hin th ca cc ngy trong thng hin ti thnh cc thng trong nm hin ti.Click khc s chuyn cc nm trong thp k hin ti.Hnh ng ny cho php bn d dng chuyn n mt ngy trong qu kh hoc tng lai t iu khin calendar. Thuc tnh: Tn M t Animated Chuyn sang ch hot hnh ClearTime Xa thi gian CssClass Lp Css c dng nh dng calendar DaysModeTitleFormat nh dng ngy c hin th,gi tr mc nh l MMMM/YYYY DefaultView Xc nh hoc thit lp hin th mc nh ca calendar.Mc nh l th hin cc ngy EnabledOnClient Hnh vi ny c sn cho phn t hin ti FirstDayOfWeek Xc nh hoc thit lp ngy u tin ca tun Format nh dng chui c dng th hin ngy c chn,mc nh l d OnClientDateSelectionChan Xc nh hoc thit lp on m c thc thi khi mt ged ngy mi c chn OnClientHidden Thit lp on m c thc 350hin gay sau khi calendar va n OnClientHiding Thit lp on m thc 350hin gay trc khi calendar n OnClientShowing Thc thi on m lnh ngay trc khi calendar va hin OnClientShown Thc thi on m lnh ngay sau khi calendar va hin PopupButtonID ID ca iu khin hin calendar khi click,nu gi tr khng c thit lp,calendar s c hin khi a tr chut vo text box PopupPosition Thit lp v tr hin th ca calendar,mc nh l gc di bn tri SelectedDate Thit lp ngy m calendar c khi to cng TodaysDateFormat nh dng chui hin th ngy hin ti,mc nh l MMMM d YYYY Pha Client Lu hnh ni b Trang 350

Thuc tnh: Tn animated button clearTime cssClass dayCell daysModeTitleFormat defaultView enabled firstDayOfWeek format isOpen popupPosition selectedDate todayButton todaysDate todaysDateFormat visibleDate Phng thc: Tn Blur Dispose focus hide initialize invalidate raiseDateSelectionChanged raiseHidden raiseHiding raiseShowing raiseShown resumeLayout show suspendLayout S kin: Lu hnh ni b Trang 351 M t Chuyn sang ch hot hnh Button c dng hin th calendar(ty chn) Xa thi gian trong khung sa i ngy gi Lp css c dng chnh sa hin th calendar Ly mt ngy trong ct v hng c ch ra nh dng c s dng cho tiu trong ch ngy Hin th mc nh ca calendar khi n hin ra Bt chc nng calendar cho phn t hin hnh Xc lp ngy u tin ca tun nh dng c dng cho gi tr ngy Cho php calendar hin th V tr ca calendar khi n hin th.C th l BottomLeft(mc nh),BottomRight,TopLeft,TopRight Gi tr ngy hin th trong textbox Button c dng chn ngy hin ti Ngy s dng cho Today nh dng ca todaysDate Ngy hin ti c nhn thy trong calendar M t V hiu ha cc hnh vi n calendar Khi to thnh phn v tham s cho hnh vi Thc hin b tr ca hnh vi tr phi b tr b treo Kch hot s kin DateSelectionChanged Kch hot s kin Hidden Kch hot s kin Hidding Kch hot s kin Showing Kch hot s kin Shown Tip tc b tr hnh vi v thc hin bt k yu cu b tr no Hin th calendar Dng hin th

Tn dateSelectionChanged

hidden hiding showing shown Th d: <ajaxToolkit:Calendar runat=server TargetControlID=Date1 CssClass=ClassName Format=MMMM d, yyyy PopupButtonID=Image1 />

M t Thm iu khin s kin cho s kin SelectionChanged Thm iu khin s kin cho s kin hidden Thm iu khin s kin cho s kin hidding Thm iu khin s kin cho s kin showing Thm iu khin s kin cho s kin shown

11.6.7 CascadingDropDown Control. Pha Server nh ngha lp m rng CascadingDropdown. Thuc tnh: Tn M t Category mc ca DropDownList(s dng khi lin h vi mt web service) ContextKey Trng thi ca ngi dng/trang c ch ra cung cp n mt phng thc c m t bi ServiceMethod/ServicePath.Nu context key c s dng,n s c cng mt kiu vi mt tham s c tn l contextKey kiu string EmptyText Chui k t hin th kh danh sch rng EmptyValue Gi tr hin th khi danh sch rng LoadingText Chui k t hin th khi danh sch load d liu ParentControlID ID ca phn cha DropDownList(phn ni dung m DropDownList s dng) PromptText Chui c hin th khi ngi dng khng la chn,nu b qua,mc u tin s c chn PromptValue Gi tr ca la chn c hin th bi DropDownList th hin PromtText SelectedValue Gi tr c la chn ServiceMethod Tn ca phng thc web service ServicePath ng dn n web service UseContextKey S dng hay khng thuc tnh ContextKey,n s t ng s dng nu thuc tnh ContextKey cha c thit lp(c client v server),nu ContextKey c s dng,n s c cng gi tr vi tham s contextKey vi kiu String Lu hnh ni b Trang 352

Phng thc: Tn M t Constructor Constructor CascadingDropDown_ClientStateV Hin th DropDownList vi cc gi tr ca n aluesLoaded(System.Object, System.EventArgs) ParseKnownCategoryValuesString( Phng thc dng chuyn i nh dng System.String) ring c dng lin h vi cc mc QuerySimpleCascadingDropDown Phng thc cung cp mt hin thc n gin Document(System.Xml.XmlDocum ca phng thc dng truy vn tp d liu ent, System.String[], v tr v thnh phn ca dropdown System.Collections.Specialized.Stri ngDictionary, System.String) QuerySimpleCascadingDropDown Phng thc cung cp mt hin thc n gin Document(System.Xml.XmlDocum ca phng thc dng truy vn tp d liu ent, System.String[], v tr v thnh phn ca dropdown System.Collections.Specialized.Stri ngDictionary, System.String, System.Text.RegularExpressions.R egex) ShouldSerializeServicePath Ngn dch v chy khi n rng Pha Client Phng thc: Tn M t Category mc ca drop down contextKey Trng thi ca ngi dng/trang c ch ra cung cp n mt phng thc c m t bi ServiceMethod/ServicePath.Nu context key c s dng,n s c cng mt kiu vi mt tham s c tn l contextKey kiu string EmptyText Chui k t hin th kh danh sch rng EmptyValue Gi tr hin th khi danh sch rng LoadingText Chui c hin th khi drop down ly gi tr t web service ParentControlID ID ca phn t cha trong h thng cc drop down PromptText Hin th nh l mc u tin trong drop down PromptValue Gi tr ca la chn c hin th bi Dropdown th hin PromtText SelectedValue Gi tr c la chn trong drop down ServiceMethod Tn ca phng thc gi web service ServicePath ng dn n web service useContextKey S dng hay khng thuc tnh ContextKey,n s t ng s dng nu thuc tnh ContextKey cha c thit lp(c client v server),nu ContextKey c s dng,n s c cng gi tr vi tham s contextKey vi kiu String Lu hnh ni b Trang 353

Phng thc: Tn dispose initialize raisePopulated raisePopulating raiseSelectionChanged S kin: Tn populated populating selectionChanged M t V hiu cc hnh vi Khi to cc hnh vi Kch hot s kin Populated Kch hot s kin Populating Kch hot s kin SelectionChanged M t Thm iu khin s kin cho s kin populated Thm iu khin s kin cho s kin populating Thm iu khin s kin cho s kin selectionChanged

Th d: <ajaxToolkit:CascadingDropDown ID="CDD1" runat="server" TargetControlID="DropDownList2" Category="Model" PromptText="Please select a model" LoadingText="[Loading models...]" ServicePath="CarsService.asmx" ServiceMethod="GetDropDownContents" ParentControlID="DropDownList1" SelectedValue="SomeValue" /> 11.6.8 CollapsiblePanel Control Mt lp m rng cho php thm hnh vi m rng hay thu hp mt iu khin ASP.NET.Phn ni dung c gn m rng sau c th m rng ra hoc thu hp li bi ngi dng,mt cch th cng nh hin th hoc giu ni dung hay m rng ton b khong trng hin c. Pha Server. Phng thc: Tn M t AutoCollapse Nu gi tr l true v trng thi ca panel l expanded th kh di chuyn con tr chut ra khi panel th n t ng collapse AutoExpand Ngc li,nu gi tr l true v trng thi ca panel l collapse th khi di chuyn chut vo n s t ng expanded CollapseControlID ID ca panel c gn vi iu khin.Panel s thu gn khi iu khin kch hot s kin onclick pha client.Nu n cng gi tr vi ExpandControlID,CollapsiblePanel s t ng chuyn ch khi click vo iu khin ny Collapsed Tn hiu khi to trng thi thu gn ca iu khin.Lu l Lu hnh ni b Trang 354

CollapsedImage CollapsedSize

CollapsedText

ExpandControlID

ExpandDirection ExpandedImage ExpandedSize

ExpandedText

ImageControlID

ScrollContents SuppressPostBack

TextLabelID Lu hnh ni b

n khng lm cho iu khin m rng thu hp li khi khi to,m n thng bo vi extender trng thi ca panel Hnh nh c hin th khi panel c thu hp v ImageControlID c thit t Kch thc ca panel khi n trng thi thu hp. trnh b co gin trang khi panel c khi to,thit lp chiu cao(hoc chiu rng) ca panel vi mt gi tr no v thit lp thuc tnh Collapse l true.Gi tr mc nh l -1 ,ch ra rng Panel s khi to gi tr CollapsedSize da trn kch thc ca i tng. on text hin th trong trng thi ng.Khi panel trng thi ng,ni dung bn trong iu khin tham chiu ti thuc tnh TextLabelID s c thay th bi on text ny.Thuc tnh ny cng c dng nh mt on text thay th mt hnh nh nu ImageControlID c thit lp ID ca iu khin pha server.Panel s c m nu iu khin ny kch hot s kin onclick,nu n c cng gi tr voiwsCollapsedControlID,panel s t ng chuyn ch khi click vo iu khin ny Kch thc dng m rng hoc thu hp theo chiu ngang hoc hiu dc Hnh nh c hin th khi panel c m rng v thuc tnh ImageControlID c thit lp Kch thc ca panel khi n trng thi m , trnh trang b co gin khi khi to,thit lp chiu rng ca panel vi mt gi tr no ,v thuc tnh Collapse l false,gi tr mc nh l 1,iu c ngha l panel s c khi to ExpanedSize trn c s kch thc ca i tng Vn bn c hin th trong trng thi m rng,khi panel c m,ni dung bn trong ca iu khin tham chiu bi thuc tnh TextLabelID s c thay th bi on text ny,phn text m rng cng c s dng nh l phn thay th cho hnh nh nu ImageControlID c thit lp ID ca hnh nh th hin trng thi hin ti ca panel,khi trng thi thu gn ca panel thay i,hnh nh ngun s thay i t ExpandedImage sang CollapsedImage.Chng ta cng s dng ExpandedText v CollapsedText nh l on text thay th hnh nh nu chng c yu cu Xc nh phn ni dung ca panel s c cun hoc che i nu chng khng nm gn bn trong kch thc m rng Xc nh CollapsiblePanelBehavior s ngn chn x l s kin click ca iu khin tham chiu n CollapseControlID hoc ExpandControlID.mc nh gi tr ny l false,ngoi l i vi tag a ID ca mt label th hin trng thi hin ti ca Panel.Khi trng thi thu gn ca panel b thay i,phn ni dung HTML Trang 355

s c thay th bi on text m t trng thi ca panel Phng thc: Tn M t Constructor Constructor mc nh Pha Client. CollapsiblePanelBehavior cho php bn thm mt phn c th thu gn vo trang web ca bn. Thuc tnh: Tn M t AutoCollapse Cho php panel t ng thu hp nu con tr chut di chuyn ra ngoi panel AutoExpand Cho php panel t ng m rng nu tr chut di chuyn vo bn trong panel CollapseControlID ID ca iu khin c dng thu gn phn ni dung khi click Collapsed Thit lp panel c thu gn hay khng CollapsedImage ng dn n hnh nh s c th hin phn t c ch ra ImageControlID khi panel trng thi thu gn CollapsedSize Kch thc ca panel tnh bng pixel khi n trng thi thu gn CollapsedText Phn text c th hin khi panel trng thi thu gn ExpandControlID ID ca iu khin dng m rng phn ni dung khi click ExpandDirection Ch nh hng m rng hoc thu gn ca panel(hoc theo chiu ngang Horizontal hoc theo chiu dc Vertical) ExpandedImage ng dn n hnh nh s hin th phn t c ch ra bi ImageControlID khi panel trng thi m rng. ExpandedSize Kch thc ca panel tnh bng pixel khi n trng thi m rng ExpandedText Phn text hin th khi panel trng thi m rng ImageControlID ScrollContents Cho php thm hay khng thanh cun khi phn ni dung hin th qu gii hn khung panel(phn ni dung s b mt nu thit lp l false) SuppressPostBack Cho php hay khng to postbacks khi CollapseControlID v ExpandControlID c click TargetHeight Rng buc chiu cao ca panel TargetWidth Rng buc chiu rng ca panel TextLabelID ID ca phn t m trng thi ca panel th hin Phng thc: Tn M t collapsePanel Thu gn panel.Mt hm public cho php ngi dng gi Lu hnh ni b Trang 356

Dispose expandPanel Initialize raiseCollapseComplete raiseCollapsed raiseCollapsing raiseExpandComplete raiseExpanded raiseExpanding togglePanel

khi h mun thu gn panel bng lnh. V hiu ha cc hnh vi. M rng panel. Khi to cc hnh vi Kch hot s kin CollapseComplete Kch hot s kin Collapsed Kch hot s kin Collapsing Kch hot s kin ExpandCompete Kch hot s kin Expanded Kch hot s kin Expanding Qun l s kin m rng hay 357hug on panel (trn trng thi hin ti ca n).y l mt hm public s c gi thay cho _toggle nu bn mun m hay ng panel bng lnh

S kin: Tn M t collapseComplete Thm iu khin s kin cho s kin collapseComplete collapsed Thm iu khin s kin cho s kin collapsed collapsing Thm iu khin s kin cho s kin collapsing expandComplete Thm iu khin s kin cho s kin expandComplete expanded Thm iu khin s kin cho s kin expanded expanding Thm iu khin s kin cho s kin expanding Th d: <ajaxToolkit:CollapsiblePanelExtender ID=cpe runat=Server TargetControlID=Panel1 CollapsedSize=0 ExpandedSize=300 Collapsed=True ExpandControlID=LinkButton1 CollapseControlID=LinkButton1 AutoCollapse=False AutoExpand=False ScrollContents=True TextLabelID=Label1 CollapsedText=Show Details ExpandedText=Hide Details ImageControlID=Image1 ExpandedImage=~/images/collapse.jpg CollapsedImage=~/images/expand.jpg ExpandDirection=Vertical /> Lu hnh ni b Trang 357

11.6.9 ColorPicker Control Phn m rng ColorPicker cho php bn hin th mt bng pop-up mu khi con tr di chuyn n phn t input.Bn c th gn ColorPicker vo bt c textbox no ca ASP.NET.N cung cp mt hm cho php la chn mu pha client vi giao din ngi dng.Ngoi ra,bn c th ch ra mt button hin th mt popup la chn mu v mt iu khin cho php xem trc mu t bng mu.Bn c th cung cp mt textbox khi m ngi dng nhp vo mt gi tr mu th ColorPicker c th hin th mu tng ng nu mu khng c trong bng mu mc nh. Pha Server Thuc tnh: Tn M t TargetControlID ID ca textbox PopupButtonID ID ca iu khin c dng hin th bng popup chn mu,nu gi tr khng c thit lp,bng mu s t ng hin th khi textbox ch nh TargetControlID c chn SampleControlID ID ca iu khin dng hin th mu c chn.Nu gi tr ny c thit lp v 358ang chn mu ang m,mu nn ca iu khin c ch ra th hin mu m tr chut ang tr ti,nu gi tr khng c thit lp,mu c chn s khng hin th PopupPosition Xc nh v tr m bng la chn mu s hin th so vi v tr ca textbox m extender ny gn vo,c th l BottomLeft,BottomRight,TopLeft,TopRight SelectedColor Gi tr mu m bng mu ColorPicker to ra lc khi to Phng thc: Tn M t OnClientColorSelectionChan Hm javascript s c gi khi s kin ged colorSelectionChanged xy ra. Pha Client Thuc tnh: Tn M t button Thit lp mt i tng kiu Sys.UI.DomElement th hin mt button dng hin bng mu,thuc tnh ny l ty chn sample Thit lp mt i tng kiu Sys.UI.DomElement th hin mt phn t dng xem trc mu va c chn hay mu m tr chut ang tr vo,thuc tnh ny l ty chn selectedColor Thit lp mt chui cha gi tr mu c th hin trong textbox enabled Thit lp mt gi tr kiu bool ch ra rng bng mu c hiu lc i vi phn t hin ti hay khng popupPosition Thit lp mt i tng kiu Sys.UI.DomElement th hin v tr m bng mu s xut hin tng ng vi textbox,cc gi tr c Lu hnh ni b Trang 358

th l BottomLeft,BottomRight,TopLeft,TopRight Phng thc: Tn M t Initialize Khi to bng mu dipose V hiu ha bng mu raiseColorSelectionChanged Kch hot s kin ColorSelectionChanged raiseShowing Kch hot s kin Showing raiseShown Kch hot s kin Shown raiseHiding Kch hot s kin Hiding raiseHidden Kch hot s kin Hidden show Hin th bng mu hide n bng mu S kin: Tn M t colorSelectionChanged Thm mt iu khin s kin cho s kin colorSelectionChanged showing Thm mt iu khin s kin cho s kin Showing shown Thm mt iu khin s kin cho s kin Shown hiding Thm mt iu khin s kin cho s kin Hiding hidden Thm mt iu khin s kin cho s kin Hidden Th d: <asp:TextBoxID=TextBox1runat=server></asp:TextBox> <asp:PanelID=Panel1runat=serverstyle=width:18px;height:18px;border:1px solid #000;margin:0 3px;float:left> </asp:Panel> <asp:ColorPickerExtender ID=ColorPickerExtender1runat=server TargetControlID=TextBox1PopupPosition=TopLeftSampleControlID=Panel1> </asp:ColorPickerExtender> 11.6.10 ComboBox Control ComboBox l mt iu khin ca ASP.NET AJAX ,n ging nh AutoCompleteExtender,kt hp linh hot vi mt Textbox vi mt danh sch ty chn cho php ngi dng c th la chn.N c cc thuc tnh,hnh vi hay quy c t tn tng t nh trn Form combobox,v c cng lp c s nh l ListBox,BulletedList v DropDownList ca web control.Tht vy,ComboBox c xem nh l DropDownList nhng li c th g trc tip vo nh l textbox. Lm vic vi ComboBox cng ging nh lm vic vi DropDownList.N c cng tt c cc thuc tnh v s kin ca DropDownList,vi mt vi thuc tnh v s kin khc na.u tin,n c th c cu hnh ngn chn hoc cho php ngi dng nhp chui m khng trng khp vi cc mc trong danh sch.Khi ngi dng g mt Lu hnh ni b Trang 359

chui trng khp vi mt mc trong danh sch,ComboBox cng c th c cu hnh t ng hon tt chui da trn c s nhng k t c g, hin th danh sch v nh du phn t u tin trng khp,hoc lm c hai ng thi.Khi ngi dng g mt chui khng trng khp vi mt mc no trong danh sch,ComboBox kch hot s kin ItemInserting v ItemInserted m c th iu khin c trong qu trnh postback.Ngoi cc hnh vi c bit ,ComboBox hot ng nh mt DropDownList. ComboBox ging nh l mt phn b sung ch khng phi l thay th cho AutoCompeleExtender.Mc d n cng c th p ng cng mt yu cu v giao din ngi dng. Thuc tnh: Tn M t DropDownStyle Xc nh xem ngi dng c c php g mtchui m khng trng khp vi mt mc no trong danh sch hay khng,v cho php danh sch lun lun c hin th.Nu gi tr l DropDownList,ngi dng khng c php g chui m khng trng khp vi mt mc trong danh sch.Nu l DropDown (gi tr mc nh) th bt k chui no cng c chp nhn.Nu l Simple th bt k chui no cng c chp nhn v danh sch lun lun c hin th bt k gi tr no ca AutoCompleteMode AutoCompleteMo Xc nh bng cch no ComboBox t ng hon tt chui va de nhp vo,nu gi tr l Suggest,ComboBox s hin th danh sch,t m mc trng khp u tin tm thy,v nu cn thit,mc c nh du s c cun ti,nu gi tr l Append,ComboBox s ni cc phn cn li ca mc u tin trng khp vi phn m ngi dng g vo v t m phn c ni,nu gi tr l SuggestAppend,c hai hnh vi trn c p dng,nu l None(gi tr mc nh),tnh nng t ng hon tt ca ComboBox s b v hiu. CaseSensitive C phn bit k t hoa thng hay khng,mc nh l khng (false) RenderMode Ch ra l ComboBox l mt phn t HTML mc Inline hay Block,mc nh l Inline ItemInsertLocati Xc nh mt item mi c thm vo l Append hay l on Prepend khi chng c thm vo trong danh sch,hoc thm chng chn vo theo th t Alphabet trn c s Text hay Value,mc nh l Append ListItemHoverCs Khi chng c thit lp,thay th style mc nh c p dng sClass t m mc trong danh sch vi mt lp css ListItem Mt hoc nhiu iu khin con c dng khai bo cc mc s c thm vo danh sch ComboBox,khi gn ngun d liu,tt c ListItems s b xa b cho n khi thuc tnh AppendDataBoundItem c t l true Lp CSS. Tn M t Lu hnh ni b Trang 360

.ajax__combobox_inputcontainer V tr ca button v textbox nhp .ajax__combobox_textboxcontainer Css cho phn textbox .ajax__combobox_buttoncontainer Css cho phn button .ajax__combobox_itemlist Css cho danh sch mc Th d: <ajaxToolkit:ComboBox ID=ComboBox1 runat=server DropDownStyle=DropDown AutoCompleteMode=None CaseSensitive=false RenderMode=Inline ItemInsertLocation=Append ListItemHoverCssClass=ComboBoxListItemHover <asp:ListItem></asp:ListIem> </ajaxToolkit:ComboBox> .CustomComboBoxStyle .ajax__combobox_textboxcontainer input { background-color: #ADD8E6; border: solid 1px Blue; border-right: 0px none; } .CustomComboBoxStyle .ajax__combobox_buttoncontainer button { background-color: #ADD8E6; border: solid 1px Blue; } 11.6.11 ConfirmButton Control ConfirmButton l mt extender n gin bt s kin click mt button v hin th mt thong bo n ngi dung.Nu button OK c click,hm s c x l bnh thng,nu khng,s kin click s b b qua v button s khng thc hin hnh vi mc nh ca n,thay vo ,mt on m s c thc thi nu thuc tnh OnClientCancel c thit lp.N tht s hu ch xa 361ien kt hoc bt c th j khc yu cu xc thc t ngi dng. Pha Server Thuc tnh: Tn M t ConfirmOnFormSubmit True nu hp thoi xc thc s c chy trn form ConfirmText Chui s c hin th bn trong hp thoi DisplayModalPopupID Ch ra ID ca ModalPopupExtender c dng trong window.confirm OnClientCancel Thit lp m lnh pha client s c thc thi khi button cancel c click trn hp thoi PostBackScript Ch ra on m c chy khi to postback Lu hnh ni b Trang 361

Phng thc: Tn OnLoad(System.EventArgs) RegisterDisplayModalPopup M t Onload override ng k phn ca DisplayModalPopupID c dng vi ConfirmButton

Pha Client Thuc tnh: Tn ConfirmOnFormSubmit ConfirmText DisplayModalPopupID OnClientCancel M t True nu hp thoi xc thc s c chy trn form Chui s c hin th bn trong hp thoi Ch ra ID ca ModalPopupExtender c dng trong window.confirm Thit lp m lnh pha client s c thc thi khi button cancel c click trn hp thoi Ch ra on m c chy khi to postback

PostBackScript Phng thc: Tn M t dispose V hiu cc hnh vi initialize Khi to cc hnh vi raiseHidden Kch hot s kin Hidden raiseShowing Kch hot s kin Showing WebForm_OnSubmit S kin: Tn M t hidden Thm iu khin s kin cho s kin hidden showing Thm iu khin s kin cho s kin showing Th d: <ajaxToolkit:ConfirmButtonExtender ID=cbe runat=server TargetControlID=LinkButton1 ConfirmText=Are you sure you want to click this? OnClientCancel=CancelClick />

11.6.12 DragPanel Control DragPanel extender cho php ngi dng d dng thm mt phn c th ko i c trong iu khin ca h.DragPanel iu khin bt k panel no ca ASP.Net v thm mt tham s ni ln iu khin c dng nh l c th ko i c.Khi c khi to,ngi dng c th thoi mi ko panel quanh trang web s dng extender ny. Thuc tnh: Lu hnh ni b Trang 362

Tn TargetControlID DragHandleID

M t ID ca panel mun ko c ID ca mt iu khin c xem nh l iu khin ko th ca panel,khi ngi dng click v ko iu khin ny,panel s di chuyn theo

11.6.13 DynamicPopulate Control. DynamicPopulate l mt extender n gin thay th ni dung ca mt control vi mt kt qu ca web service hay phng thc c gi.Phng thc c gi tr v mt chui HTML t vo phn t ch. Pha Server Thuc tnh: Tn M t CacheDynamicResults Dng lu kt qu ca ln truy vn trc v khng ly thm ln na sau ln np u tin ClearContentsDuringUpdate Cho php chng ta xa ni dung ca phn t ch hay khng khi vic cp nht bt u ContextKey Key gip bn c th gi c web service,thuc tnh ny l ty chn CustomScript Customscript c th c s dng eval hm JavaScript s gi tr chui thay i ni dungiu khin. Phng php ny phi gi tr chui v s c gi l thay v phng thc Service hay Page PopulateTriggerControlID ID ca iu khin gi th tc thay i ni dung ca phn t ch,s thay i s xy ra bi s kin click ServiceMethod Phng thc ca web service gi ServicePath ng dn n web service c gi,hoc nu thuc tnh ny trng,phng thc ca trang s c gi. UpdatingCssClass Lp css c dng trong qu trnh update Phng thc: Tn M t CheckIfValid(System.Boolea Kim tra nu cc thuc tnh c thit lp khng n) ng ShouldSerializeServicePath Ngn khi to ng dn n dch v nu khng c ServiceMethod no c cung cp Pha Client Thuc tnh: Tn M t CacheDynamicResults Dng lu kt qu ca ln truy vn trc v khng ly thm ln na sau ln np u tin ClearContentsDuringUpdate Cho php chng ta xa ni dung ca phn t ch hay khng khi vic cp nht bt u Lu hnh ni b Trang 363

ContextKey CustomScript

PopulateTriggerControlID ServiceMethod ServicePath

UpdatingCssClass Phng thc: Tn M t dispose V hiu cc hnh vi initialize Khi to cc hnh vi populate Ly ni dung v gn chng vo phn t ch raisePopulated Kch hot s kin Populated raisePopulating Kch hot s kin Populating setStyle Thit lp kiu trnh din S kin: Tn M t populated Thm iu khin s kin cho s kin populated populating Thm iu khin s kin cho s kin populating Th d: <ajaxToolkit:DynamicPopulateExtender ID=dp runat=server TargetControlID=Panel1 ClearContentsDuringUpdate=true PopulateTriggerControlID=Label1 ServiceMethod=GetHtml UpdatingCssClass=dynamicPopulate_Updating />

Key gip bn c th gi c web service,thuc tnh ny l ty chn Customscript c th c s dng eval hm JavaScript s gi tr chui thay i ni dung iu khin. Phng php ny phi gi tr chui v s c gi l thay v phng thc Service hay Page ID ca iu khin gi th tc thay i ni dung ca phn t ch,s thay i s xy ra bi s kin click Phng thc ca web service gi ng dn n web service c gi,hoc nu thuc tnh ny trng,phng thc ca trang s c gi. Lp css c dng trong qu trnh update

11.6.14 HTMLEditor Control HTMLEditor l mt iu khin ASP.NET AJAX cho php bn d dng to hoc sa i ni dung HTML.Cc button khc trong thanh cng c c dng bin tp ni dung.Bn c th thy cc th HTML hoc ti liu xem trc. Thuc tnh: Tn M t ActiveMode Kch hot panel dng bin tp khi iu khin c np Lu hnh ni b Trang 364

Nu gi tr l true,khung bin tp s c chn v con tr s c t vo trong n (Design hoc HTML text)khi trang c khi to hoc khung son tho thay i Content Thit lp ni dung ca HTML Editor CssClass Lp css dng nh ngha giao din cho HTMLEditor. DesignPanelCssPath Thit lp ng dn ca file css c dng ni dung trong HTMLEditor biu hin ch Desig.Nu khng thit lp,file css mc nh s c dng. DocumentCssPath Thit lp ng dn ca file css c dng ni dung trong HTMLEditor biu hin ch Design hoc Preview.Nu khng thit lp,file css mc nh s c dng. Height Thit lp chiu cao ca khung son tho HtmlPanelCssClass Lp css nh ngha giao din cho ch HTML text IgnoreTab Nu gi tr l true,nt tab s khng c hiu lc InitialCleanUp Nu gi tr l true,ni dung ca HTMLEditor s b xa khi c np lc khi to NoScript Nu gi tr l true,javascript s b v hiu ha NoUnicode Nu gi tr l true,tt c cc k t Unicode s c thay th bng &#code SuppressTabInDesignM Nu gi tr l true,s khng c khong trng no c t ode khi nhn tab trong ch Design.nt tab mc nh s c x l trong trng hp ny Width Thit lp chiu rng ca khung bin tp Phng thc: Tn M t OnClientActiveModeChanged Phn m s c thc 365his au khi ch hot ng thay i OnClientBeforeActiveModeCh Phn m s c thc thi trc khi ch hot anged ng thay i Cc lp css ca HTMLEditor: Tn M t ajax__htmleditor_editor_container Phn t bao gm mi phn t khc trong HTMLEditor ajax__htmleditor_editor_toptoolbar Thit lp cho button ajax__htmleditor_editor_editpanel Thit lp cho khung son tho ajax__htmleditor_editor_bottomtoolba Thit lp cho button bn di(cc ch ) r ajax__htmleditor_toolbar_button Thit lp cho mt nt ca toolbar ajax__htmleditor_toolbar_button_hov Thit lp cho mt button ca toolbar khi er a chut vo n div.ajax__htmleditor_toolbar_button Thit lp cho <label>ca toolbar AutoFocus Lu hnh ni b Trang 365

label div.ajax__htmleditor_toolbar_button Thit lp cho <select>ca toolbar select div.ajax__htmleditor_toolbar_button select option 11.6.15 ListSearch Control ListSearch extender cho php bn tm kim mt mc trong ListBox hoc DropDownList trn c s cc k t m bn nh.Mt thng ip s c hin th khi bn click vo danh sch c th c ty chnh ph thuc vo lp css v v tr ca n. Thuc tnh: Tn M t PromptText Li nhn hin th khi ListBox hay DropDownList c tr vo.Mc nh l Type to search.Dng text ny s c thay th bi cc k t khi ngi dng nhp vo PromptCssClass Tn ca lp Css c p dng vo PromtText PromptPosition Xc nh ni m tin nhn s c hin th pha trn hay di ca ListBox,mc nh l pha trn QueryPattern Xc nh bng cch no cc k t c g vo s c s dng trong cc truy vn tm kim,mc nh l kt qu c truy vn t nhng k t c g vo u tin IsSorted Xc nh nu mt mc c thm vo trong danh sch s c sp xp,mc inh l khng sp xp,nu c thit lp l true,n cho php m lnh s tm kim nhanh hn thay v xc nh s trng khp trc khi tm kim QueryTimeout Ch ra rng cc truy vn tm kim s b reset sau khong thi gian nh mc cho php m vn khng c kt qu no c tm thy,mc nh l 0,ngha l khng t ng reset Animations To hiu ng cho ListSearch extender Phng thc: Tn M t OnShow Hiu ng s c chy mi khi thng bo c hin ra. OnHide Hiu ng c chy khi thng bo n i Th d: <ajaxToolkit:ListSearchExtender id=LSE runat=server TargetControlID=ListBox1 PromptText=Type to search PromptCssClass=ListSearchExtenderPrompt PromptPosition=Top AutoResetTimeout=0 IsSorted=true/> 11.6.16 MaskedEdit Control

Lu hnh ni b

Trang 366

MaskedEdit gn vo mt textbox hn ch cc loi vn bn c nhp vo.MaskedEdit p mt mt mt n vo khung nhp m ch cho php mt s loi k t / vn bn c nhp vo. Cc d liu c h tr nh dng l: S, Ngy, Thi gian, v datetime. MaskedEdit s dng cc thit lp culture quy nh ti cc thuc tnh CultureName. Nu khng c quy nh cc thit lp culture s c ging nh trang: Ting Vit (Vit Nam). Thuc tnh: Tn M t MaskType Loi hp l thc hin: None khng cn hp l Number chp nhn kiu s Date chp nhn kiu ngy Time chp nhn kiu thi gian DateTime chp nhn c ngy v thi gian Mask Characters and 9 ch c cc k t s Delimiters L ch c cc ch ci $ - ch c cc ch ci v khong trng C ch c cc k t v phn bit hoa thng A ch c t hoc k t N ch c s hoc k t ? bt k k t no / - du phn cch ngy : - du phn cch thi gian . du phn cch thp phn , - du phn cch hng ngn \ - k t ESC { - bt u k t xc nh s lp li ca mt n } k t kt thc s lp li ca mt n Nu gi tr l true s hin th k hiu AM/PM True nu chp nhn k t - None:khng hin th k t - Left:Hin th k t - pha bn tri ca mt n Right:hin th k t - bn phi mt n T ng in cc k t trng nu ngi dng khng g vo MaskType=Number in vo cc k t 0 MaskType=Time in vo gi hin ti MaskType=Date in vo ngy hin ti MaskType=DateTime in vo ngy gi hin ti Trang 367

AcceptAMPM AcceptNegative

AutoComplete

Lu hnh ni b

AutoCompleteValue Century ClearMaskOnLostFocus ClearTextOnInvalid ClipboardEnabled ClipboardText DisplayMoney

ErrorTooltipCssClass ErrorTooltipEnabled Filtered InputDirection

MessageValidatorTip PromptChararacter UserDateFormat UserTimeFormat OnFocusCssClass OnFocusCssNegative OnBlurCssNegative

OnInvalidCssClass CultureName Th d: <ajaxToolkit:MaskedEditExtender TargetControlID=TextBox2 Mask=9,999,999.99 MessageValidatorTip=true OnFocusCssClass=MaskedEditFocus OnInvalidCssClass=MaskedEditError MaskType=Number InputDirection=RightToLeft AcceptNegative=Left DisplayMoney=Left Lu hnh ni b

K t mc nh c dng khi AutoComplete c hiu lc Th k mc nh c dng khi mt n ngy ch c 2 k t th hin nm B mt n khi textbox khng c tr vo Xa textbox khi nhp vo chui ko hp l Cho php copy/paste vi clipboard Chui hin th c dng khi thc hin dn t clipboard Ch ra bng cch no k t tin t c th hin None:khng hin th k t $ Left:Hin th k t $ pha bn tri ca mt n Right:hin th k t $ bn phi mt n Lp css cho phn tooltip Hin th tin nhn kiu tooltip khi r chut vo textbox K t hp l cho mt n kiu C(phn bit hoa thng) Kiu nhp LeftToRight tri qua phi RightToLeft phi qua tri Tin nhn hin th khi sa i textbox Du nhc cho k t khng ch nh nh dng ngy ty chnh nh dng thi gian ty chnh Lp css c dng khi textbox c tr vo Lp css c dng khi textbox c tr vo vi gi tr m Lp css c dng khi textbox khng c tr vo vi gi tr m Lp css c dng khi chui khng hp l Tn ca culture c s dng

Trang 368

ErrorTooltipEnabled=True/> 11.6.17 ModalPopup Control Moalpopup extender cho php mt trang c th hin th ni dung cho ngi dng theo kiu modal ,tc l ngn cn ngi dng tc ng vo phn cn li ca trang.Ni dung modal c th c hin th trn nn ca trang v vi kiu ty chn p dng vo n.Khi hin th,ch c ni dung modal c th tng tc c,click vo phn cn li ca trang khng c hin tng g.Khi ngi dng tng tc vi ni dung kiu modal,click vo nt Ok hoc Cancel s tt ni dung modal v chy on m m ngi dng thit lp.on m c p dng vi bt k s thay i no trong khi ch modal ang hot ng.Nu postback c yu cu,n gin cho php iu khin OK/Cancel v trang s c np li.Bn cng c th ty chnh v tr hin th ca popup vi thuc tnh X v Y,mc nh l chnh gia mn hnh,tuy nhin nu ch cn X hoc Y c xc nh sau n l trung tm theo chiu dc hoc chiu ngang. Thuc tnh: Tn M t TargetControlID ID ca phn t kch hot popup modal PopupControlID ID ca phn t hin th nh l popup modal BackgroundCssClass Lp css p dng cho nn khi popup modal hin th DropShadow T ng thm 369ong cho popup modal OkControlID ID ca phn t hy b modal popup OnOkScript M lnh c chy khi modal popup b hy b bi OkControlID CancelControlID ID ca phn t b qua modal popup OnCancelScript M lnh c chy khi hy b modal popup bi CancelControlID PopupDragHandleContro ID ca phn t cha tiu c dng nh l iu lID khin popup X Ta theo chiu ngang Y Ta theo chiu dc RepositionMode Ty chn xc nh nu popup cn phi thay i v tr khi ca s thay i kch thc hoc c cun Th d: <ajaxToolkit:ModalPopupExtender ID=MPE runat=server TargetControlID=LinkButton1 PopupControlID=Panel1 BackgroundCssClass=modalBackground DropShadow=true OkControlID=OkButton OnOkScript=onOk() CancelControlID=CancelButton PopupDragHandleControlID=Panel3 /> Lu hnh ni b Trang 369

11.6.18 MultiHandleSlider Control M rng MultiHandleSlider cung cp mt tnh nng m rng cho mt asp ph bin:textbox. N cho php bn chn mt gi tr duy nht, hay nhiu gi tr trong mt phm vi nht nh, thng qua mt thanh trt.N h tr mt x l, x l kp, hoc s bt k x l 370an buc vi cc gi tr ca asp: TextBox hay asp: Labe. N cng cung cp ty chn cho truy cp ch c, ty bin giao din, di chut v ko x l, cng nh h tr kh nng truy cp ca chut v bn phm. Nhiu MultiHandleSlider thit k l da trn bn gc Slider , do , bn c th xem li nhng li khuyn v gi thit k c cung cp bi cc trang trnh din ca extender . Th d, MultiHandleSlider gi li cc chc nng tooltip ging nh Slider gc. Bng cch khai bo TextBox c m rng nh l mt phn ca mt UpdatePanel, cc MultiHandleSlider c th kch hot s kin cp nht bt c khi no tin hnh x l. Bng cch thit lp cc thuc tnh RaiseChangeOnlyOnMouseUp l false, cp nht trn c xy 370an gay sau khi thay i gi tr ca MultiHandleSlider ny. Thuc tnh: Tn M t Minimum Gi tr ti thiu cho php Maximum Gi tr ti a cho php Length Chiu di ca thanh trt tnh bng pixel Decimals S lng s thp phn cho gi tr Steps S lng cc gi tr ri rc trong phm vi thanh trt Orientation xc nh xem nh hng ca thanh trt l nm ngang hoc thng ng. CssClass Phong cch tng th p dng cho thanh trt. EnableHandleAnim Nu gi tr l true,click di chuyn thanh trt s cho php ation to hiu ng khi di chuyn EnableRailClick Cho php click vo thanh trt s di chuyn iu khin gn nht n v tr va click EnableInnerRange Cho thanh trt c nhiu iu khin,xc nh vic click v Drag ko thanh trt gia 2 iu khin s di chuyn c hai cng lc EnableKeyboard Cho php gi tr thanh trt c th c thay i bng bn phm EnableMouseWhee Cho php gi tr thanh trt c th c thay i bng cch l ln con ln ca chut ShowInnerRail Vi thanh trt c nhiu iu khin,xc nh cch th hin th phn gia hai iu khin ShowHandleHover Cho php hin th mt kiu css khi ngi dng di chuyn Style chut ln trn iu khin ShowHandleDragS Kiu css khi ngi dng ko iu khin tyle InnerRailStyle Cho thanh trt c nhiu iu khin v phong cch ty chnh,xc nh bng cch no th hin InnerRailCss nh n Lu hnh ni b Trang 370

c m t,hoc s dng phng php nh trt ReadOnly Cho php ngi dng c th thay i gi tr thanh trt Increment Cho thanh trt s dng bn phm hoc chut ,xc nh s lng im tng hoc gim gi tr thanh trt HandleAnimationD Qu trnh ca hiu ng x l,tnh bng giy uration BoundControlID Cho tnh tng thch ngc,cho php s dng Slider cho mt iu khin HandleCssClass Cho tnh tng thch ngc,ch ra kiu ca x l n RaiseChangeOnly Nu gi tr l true,kch hot s kin thay i textbox ch khi OnMouseUp nh phm tri chut TooltipText Text hin th khi r chut n iu khin,gi tr {0} s c thay th cho gi tr hin ti ca thanh trt MultiHandleSlider Thuc tnh bn trong m t mi x l trn thanh trt: Targets ControlID:Textbox hoc Label gn vi iu khin. HandleCssClass:lp css c dng khi ngi dng cho iu khin HandleHoverCssClass:lp css c dng khi ngi dng r chut vo iu khin HandleDragCssClass:lp css c dng khi ngi dng ko thanh trt DecimalPlaces:s ch s cho nh dng ca gi tr Offset: S kin: Tn M t OnClientLoad S kin khi khi to thanh trt OnClientDragStart S kin khi ngi dng bt u ko thanh trt OnClientDrag S kin khi ngi dng ko thanh trt OnClientDragEnd S kin khi ngi dng kt thc ko thanh trt OnClientValueChanged S kin khi gi tr thay i Th d: <asp:TextBox ID=sliderOne runat=server AutoPostBack=true Text=0/> <ajaxToolkit:MultiHandleSliderExtender ID=multiHandleSliderExtenderOne runat=server BehaviorID=multiHandleSliderExtenderOne TargetControlID=sliderOne Minimum=-100 Maximum=100 Steps=5 Length=140 Lu hnh ni b Trang 371

BoundControlID=lblSliderOne ToolTipText={0}> </ajaxToolkit:MultiHandleSliderExtender> <asp:Label ID=lblSliderOne runat=server style=text-align:right Text=0 /> 11.6.19 MutuallyExclusiveCheckBox Control MutuallyExclusiveCheckBox l mt ASP.NET AJAX extender c th c gn vo bt k CheckBox no trong ASP.NET. Bng cch thm vo mt s hp kim tra c cng Key, ch c mt checkbox vi key c ch ra mi c th c chn.Extender ny rt hu ch khi mt s la chn l c sn nhng ch c mt ci c th c la chn, tng t nh mt nt radio. Vic s dng cc checkbox tuy nhin cho php bn chn hoc b chn mt gi tr m khng th lm c vi cc nt radio. iu ny cng cung cp mt giao din nht qun v c mong i nhiu hn s dng javascript cho php b chn mt mc RadioButton. Thuc tnh: Tn M t TargetControlID ID ca 372heckbox sa i Key Kha duy nht c dng,gn vi checkbox Th d: <ajaxToolkit:MutuallyExclusiveCheckboxExtender runat=server ID=MustHaveGuestBedroomCheckBoxEx TargetControlID=MustHaveGuestBedroomCheckBox Key=GuestBedroomCheckBoxes /> 11.6.20 NoBot Control NoBot l mt iu khin ging nh CAPTCHA nh phng, chng th rc/bot m khng cn bt k tng tc ngi dng. Phng php ny d dng b qua hn nhiu so vi mt yu cu xc thc con ngi, nhng NoBot c li ch hn l vic ang c thc hin hon ton v hnh. NoBot c l l thch hp nht cho cc trang web lu lng truy cp thp, ni m spam bi vit,nhn xt l mt vn v khng cn phi t hiu qu 100%.\ NoBot s dng mt vi k thut chng bot khc nhau: Buc trnh duyt khch hng phi thc hin mt php tnh JavaScript v xc nhn kt qu nh l mt phn ca cc postback. (Th d: vic tnh ton c th l mt s n gin, hoc cng c th lin quan n DOM bo m thm rng c lin quan n mt trnh duyt) Lm mt khong tr gia khi mt form c yu cu v khi n c th c postback. (Th d: Con ngi khng th hon thnh mt form trong vng cha y hai giy) Cu hnh mt gii hn vi s lng yu cu chp nhn c cho mi a ch IP trn mt n v thi gian. (Th d: mt con ngi dng nh khng th xc nhn mt form nhiu hn nm ln trong mt pht).

Lu hnh ni b

Trang 372

NoBot c th c kim tra bng cch vi phm bt k cc k thut ni trn:postback mt cch nhanh chng, ng li nhiu ln, hoc v hiu ho JavaScript trong trnh duyt. Thuc tnh: Tn M t OnGenerateChallengeAndR Ty chn EventHandler <NoBotEventArgs> cung esponse cp mt ty chnh thc hin cc m challenge/response ResponseMinimumDelaySe Ty chn sgiy ti thiu trc khi c mt phn ng conds (postback) c 373oil hp l CutoffWindowSeconds Ty chn s giy ca ca s ct theo di postbacks trc t mi a ch IP CutoffMaximumInstances Ty chn s lng ti a postbacks cho php bi mt a ch IP duy nht. Th d: <ajaxToolkit:NoBot ID=NoBot2 runat=server OnGenerateChallengeAndResponse=CustomChallengeResponse ResponseMinimumDelaySeconds=2 CutoffWindowSeconds=60 CutoffMaximumInstances=5 /> 11.6.21 PagingBulletedList Control PagingBulletedList l mt ASP.NET AJAX extender c th c gn vo mt BulletedList ASP.NET kim sot v cung cp cho pha my khch hnh thc sp xp phn trang. N rt linh hot v cho php bn ch nh, hoc s lng cc k t c s dng trong cc ch s nhm hoc s lng ti a ca cc mc hin th mi ch mc. Nu u vo cha c sp xp (hoc trn my ch hoc my khch), n s to ra cc ch s tiu hn nhng vn cn chc nng thch hp. Thuc tnh: Tn M t TargetControlID ID ca BulletedList ClientSort Cho php cac mc s c sp xp pha client hay khng IndexSize S lng k t trong cc nhm ch s (b qua nu MaxItemPerPage c thit lp) MaxItemPerPage S mc ti a trn mi trang (b qua thuc tnh IndexSize) Separator Du ngn c t gia cc ch s SelectIndexCssClass CSS class cho cc ch s c la chn UnselectIndexCssClass CSS class cho cc ch s m khng c la chn Th d: Lu hnh ni b Trang 373

<ajaxToolkit:PagingBulletedListExtender ID=PBLE1 runat=server TargetControlID=BulletedList1 ClientSort=true IndexSize=1 MaxItemPerPage=20 Separator= SelectIndexCssClass=selectIndex UnselectIndexCssClass=unSelectIndex /> 11.6.22 PasswordStrength Control PasswordStrength l mt ASP.NET AJAX extender c th c gn vo mt TextBox iu khin ASP.NET c s dng cho cc mc nhp ca mt khu. Cc extender PasswordStrength cho thy mnh ca mt khu trong TextBox v cp nht chnh n khi ngi dng nh mt khu. Cc ch s c th hin th mnh ca mt khu di dng tin nhn vn bn hoc vi mt ch s thanh tin trnh. Kiu dng v v tr ca c hai loi ch s c th c ty chnh. Yu cu v mnh ca mt khu cng c th c ty chnh, cho php chng ta ty chnh yu cu v mnh ca mt khu theo nhu cu. Cc tin nhn vn bn m t mnh hin ti ca mt khu cng c th c ty chnh v gi tr mc nh ca chng c h tr sn cc b ha. Chng ta khng c ccchui cho tt c ngn ng hin ti c th hin th nn chng ta c th dng mt ngn ng chung cho mt s ngn ng khc. Mt ch bo c th c s dng cung cp hng dn r 374am v nhng g thay i l cn thit t c mt mt khu mnh. Ch s ny c hin th khi ngi dng bt u g vo TextBox v c n i mi khi textbox khng c tr n. Thuc tnh: Tn M t TargetControlID ID ca TextBox nh km vo DisplayPosition Xc nh v tr hin th mnh so vi textbox StrengthIndicatorType Kiu hin th mnh ca password(kiu text hay l bar) PreferredPasswordLength di ca mt khu u tin PrefixText Vn bn c tin t hin th khi StrengthIndicatorType = text TextCssClass Lp CSS p dng cho cc hin th vn bn khi StrengthIndicatorType = Text MinimumNumericCharact S k t ti thiu ers MinimumSymbolCharacte S biu tng ti thiu rs RequiresUpperAndLower Yu cu c c k t hoa v thng CaseCharacters MinimumLowerCaseChar Ch c hiu lc nu thuc tnh acters RequiresUpperAndLowerCaseCharacters l true. Ch Lu hnh ni b Trang 374

nh s k t thng ti thiu. MinimumUpperCaseChara Ch c hiu lc nu thuc tnh cters RequiresUpperAndLowerCaseCharacters l true. Ch nh s k t hoa ti thiu. TextStrengthDescriptions Danh sch cc m t c ngn cch bi du chm phy c dng khi StrengthIndicatorType=Text(ti thiu l 2,ti a l 10,sp xp t yu nht n mnh nht) CalculationWeightings Danh sch cc gi tr s c ngn cch bi du chm phy c dng xc nh t trng mnh ca cc k t.Yu cu phi c 4 gi tr c ch 375am c tng l 100.Cc gi tr mc inh jafl 50;11;11;20.iu ny c ngha l chiu di mt khu c tnh l chim 50% trong vic tnh ton mnh ca mt khu,c k t s chim 11%,hoa-thng chim 11% v cc biu tng chim 20%. BarBorderCssClass Lp css c p dng cho bin ca thanh ch s khi StrengthIndicatorType=BarIndicator BarIndicatorCssClass Lp css c p dng cho phn bn trong ca thanh ch s khi StrengthIndicatorType=BarIndicator StrengthStyles Danh sch lp CSS c ngn cch bi du chm phy c dng ty thuc vo mnh ca mt khu.Thuc tnh ny override li thuc tnh BarIndicatorCssClass / TextIndicatorCssClass.Thuc tnh BarIndicatorCssClass / TextIndicatorCssClass khc ch n l mt thuc tnh kiu CSS ca mnh kiu text hay bar(ty thuc vo kiu la chn)bt k mnh ca mt khu.Thuc tnh ny s thay i kiu hin th da trn mnh ca mt khu cng nh s kiu c ch ra trong thuc tnh ny.Thuc tnh ny c th c ti a 10 kiu. HelpStatusLabelID ID ca label c dng hin th phn vn bn tr gip HelpHandleCssClass Lp css c p dng cho phn t tr gip c dng hin th hp thng bo m t yu cu v mt khu HelpHandlePosition V tr ca phn t tr gip so vi iu khin ch Th d: <ajaxToolkit:PasswordStrength ID=PS runat=server TargetControlID=TextBox1 DisplayPosition=RightSide StrengthIndicatorType=Text PreferredPasswordLength=10 PrefixText=Strength: Lu hnh ni b Trang 375

TextCssClass=TextIndicator_TextBox1 MinimumNumericCharacters=0 MinimumSymbolCharacters=0 RequiresUpperAndLowerCaseCharacters=false TextStrengthDescriptions=Very Poor;Weak;Average;Strong;Excellent TextStrengthDescriptionStyles=cssClass1;cssClass2;cssClass3;cssClass4;cssClas s5 CalculationWeightings=50;11;11;20 /> 11.6.23 Popup Control PopupControl l mt ASP.NET AJAX extender c th c nh km vo bt k iu khin no m mt ca s popup c hin th ni dung b sung. Ca s popup ny s c tng tc v s c t vo bn trong mt ASP.NET AJAX UpdatePanel, v vy n c th thc hin cc x l phc tp da trn my ch(bao gm c postbacks) m khng nh hng n phn cn li ca trang. Cc ca s popup c th cha bt k ni dung no, bao gm c iu khin ASP.NET pha server ,cc phn t HTML,vv 376his au cng vic ca cc ca s popup hon tt,pha server ch vic gi lnh hy b n v chy mt on m lnh c 376his quan pha my khch cp nht trang. Thuc tnh: Tn M t TargetControlID ID ca iu khin mun gn vo PopupControlID ID ca iu khin hin th Position Thit lp ty chnh v tr ca hin th popup so vi iu khin ch(top,left,376his ,bottom,center) CommitProperty Thit lp ty chn ch ra rng iu khin c gn extender ny s nhn kt qu t popup CommitScript Thit lp ty chnh on m lnh s c thc 376his au khi thit lp kt qu popup OffsetX/OffsetY S pixel chnh lch ca popup t v tr mc nh ca n c ch nh trong thuc tnh position Animations Hiu ng khi hin th popup Th d: <ajaxToolkit:PopupControlExtender ID=PopEx runat=server TargetControlID=DateTextBox PopupControlID=Panel1 Position=Bottom /> 11.6.24 Rating Control iu khin Rating cung cp mt th hin nh gi trc quan cho php ngi dng chn s lng cc ngi sao i din cho nh gi ca h. Cc nh thit k trang c th ch nh nh gi ban u, s nh gi ti a cho php, chiu v hng ca cc ngi Lu hnh ni b Trang 376

sao, v tu chnh style cho cc trng thi khc nhau c th c ca mt ngi sao. nh gi cng h tr s kin ClientCallBack cho php mt on codechy sau khi ngi s dng nh gi. Thuc tnh: Tn M t AutoPostBack Thit lp l true gi mt postback khi click vo item nh gi CurrentRating Khi to gi tr nh gi MaxRating Gi tr nh gi ti a ReadOnly Cho php s i nh gi hay khng StarCssClass Lp css cho cc ngi sao hin hin WaitingStarCssClass Lp css cho cc ngi sao trng thi ch(cha c chn) FilledStarCssClass Lp css cho cc ngi sao trng thi y EmptyStarCssClass Lp css cho cc ngi sao trng thi trng RatingAlign Cch sp cc ngi sao (ngang hay dc) RatingDirection Hng cc ngi sao l t tri qu phi hay ngc li (LeftToRightTopToBottom hoc RightToLeftBottomToTop) OnChanged S kin ClientCallBack c gi khi nh gi c thay i Tag Tham bin theo ring n chuyn n clientcallback Th d: <ajaxToolkit:Rating ID=ThaiRating runat=server CurrentRating=2 MaxRating=5 StarCssClass=ratingStar WaitingStarCssClass=savedRatingStar FilledStarCssClass=filledRatingStar EmptyStarCssClass=emptyRatingStar OnChanged=ThaiRating_Changed /> 11.6.25 ReorderList Control ReorderList l mt iu khin ASP.NET AJAX thc hin 377ang buc d liu vi danh sch lit k cc mc c th c sp xp li. sp xp li cc mc trong danh sch, ngi dng ch cn ko thanh iu khin ca mt hng n v tr mi.Thng tin phn hi c hin th di dng ha, ni mc ny c t bi ngi s dng. Cc ngun d liu c cp nht sau khi mc c ko ti v tr mi. Khi b 377ang buc vo d liu, iu khin ReorderList s hot ng ging nh nhiu iu khin databound khc. Nu d liu bn ang hin th c mt trngc sp xp th t (Th d nh truy vn sp xp theo ct ny), v ct thuc kiu s nguyn, Lu hnh ni b Trang 377

cc ReorderList c th thc hin sp xp li t ng nu thuc tnh SortOrderField c thit lp. Thuc tnh: Tn M t DataSourceID Ngun d liu c dng gn vo iu khin DataKeyField Kha ring cho d liu SortOrderField Trng i din cho th t sp xp cc mc ItemInsertLocation Xc nh ni m mt phn t mi c thm vo danh sch c th l begin hoc end DragHandleAlignmen Ni iu khin ko c gn so vi phn t,c th l t left,right,top,bottom AllowReorder Cho php ko th sp xp hay khng,mc nh l true ItemTemplate Mu hin th cc phn t trong danh sch EditItemTemplate Mu hin th cho mt dng trong ch sa i ReorderTemplate Mu c dng hin th v tr c th xung khi thc hin sp xp li,mu ny khng c gn d liu InsertItemTemplate Mu c dng th hin mt phn t mi c thm vo DragHandleTemplate Mu cho mc khi ngi dng ko sp xp li mc EmptyListTemplate Mu c dng khi danh sch rng,mc ny cng khng c gn d liu PostbackOnReorder Xc nh cho php postback hay callback khi c sp xp li,nu dng bt k hm sa i hay xa no th nn thit lp l enable Th d: <ajaxToolkit:ReorderList ID=ReorderList1 runat=server DataSourceID=ObjectDataSource1 DragHandleAlignment=Left ItemInsertLocation=Beginning DataKeyField=ItemID SortOrderField=Priority AllowReorder=true> <ItemTemplate></ItemTemplate> <ReorderTemplate></ReorderTemplate> <DragHandleTemplate></DragHandleTemplate> <InsertItemTemplate></InsertItemTemplate> </ajaxToolkit:ReorderList> 11.6.26 Resizable Control ResizableControl l mt extender c th gn vo bt k phn t no trn mt trang web v cho php ngi dng thay i kch cvi mt x l gn vo gc di bn phi Lu hnh ni b Trang 378

ca kim sot. Vic x l thay i kch c cho php ngi dng thay i kch c cc phn t nh th n l mt ca s. Phn th hin cho php thay i kch c c th c thit k bi cc nh thit k thng qua CSS. Cc ni dung bn trong phn t c th s dng CSS t ng thay i kch c ph hp vi kch thc mi. Ngoi ra, ResizableControl c hai s kin (onresizing v onresize) m ta c th nh km on m script cho php b tr logic phc tp hn. Kch thc Element c bo tn qua postbacks n my ch v thuc tnh kch thc c th truy cp c trn my khch v my ch u c th c s dng cho php thay i kch thc. ResizableControl c th gii hn chiu rng v chiu cao ti thiu,ti a ca mc tiu. Thuc tnh: Tn M t TargetControlID ID ca phn t ch HandleCssClass Tn ca lp css c dng p dng vo iu khin ResizableCssClass Tn ca lp css c dng p dng vo iu khin khi ang thay i kch thc MinimumWidth/MinimumHeight Kch thc ti thiu ca phn t ch MaximumWidth/MaximumHeight Kch thc ti a ca phn t ch HandleOffsetX/HandleOffsetY V tr ca phn t ch S kin: Tn M t OnClientResizeBegin S kin xy ra khi phn t bt u thay i kch thc OnClientResizing S kin xy ra khi phn t ang c thay i kch thc OnClientResize S kin xy ra sau khi phn t c thay i kch thc Th d: <ajaxToolkit:ResizableControlExtender ID=RCE runat=server TargetControlID=PanelImage HandleCssClass=handleImage ResizableCssClass=resizingImage MinimumWidth=50 MinimumHeight=20 MaximumWidth=260 MaximumHeight=130 OnClientResize=OnClientResizeImage HandleOffsetX=3 HandleOffsetY=3 /> 11.6.27 RoundedCorners Control Cc extender RoundedCorners lm trn gc cho cc phn t. thc hin iu ny n chn vo cc phn t trc v sau khi cc phn t c chn, do chiu cao Lu hnh ni b Trang 379

tng th ca phn t ny s thay i mt cht. Bn c th chn cc gc ca panel chcn phi c lm trn bng cch thit lp thuc tnh Corners trn extender l None, TopLeft, TopRight, BottomRight, BottomLeft, Top, Right, Bottom, Left, hoc tt c. Thuc tnh: Tn M t TargetControlID ID ca iu khin ch Radius Bn knh ca cc gc,mc nh l 5px Corners Gc c lm trn,c th l None, TopLeft, TopRight, BottomRight, BottomLeft, Top, Right, Bottom, Left, hoc tt c Th du: <ajaxToolkit:RoundedCornersExtender ID=rce runat=server TargetControlID=Panel1 Radius=6 Corners=All /> 11.6.28 Tab TabContainer l mt ASP.NET AJAX Control gip to ra mt tp hp cc Tabs c th c dng t chc cc trang ni dung. TabContainer lu tr mt s kim sot TabPanel. Mi TabPanel nh ngha mt HeaderText hoc HeaderTemplate cng nh ContentTemplate nh ngha ni dung ca n. Cc tab gn y nht vn chn sau khi postback, v trng thi Enabled ca cc tab vn cn sau khi postback. Thuc tnh ca TabContainer: Tn M t ActiveTabChanged S kin xy ra my ch khi tab b thay i sau khi postback OnClientActiveTabCha Tn ca hm javascript gn vo s kin tabChanged nged pha client CssClass Lp css nh dng cho cc tab ActiveTabIndex Tab c hin th u tin Height Thit lp chiu cao ca panel cha tnh phn header Width Chiu rng ca panel ScrollBars Cho php hin th thanh cun (None, Horizontal, Vertical, Both, Auto) trong phn 380han ca tabContainer TabStripPlacement Xc nh ch t cc tabs trn hay di tabContainer Thuc tnh cu TabPanel: Tn M t Enabled Cho php hin th cc tab cho tabPanel theo mc nh,c th c thay i phi client Lu hnh ni b Trang 380

OnClientClick HeaderText HeaderTemplate ContentTemplate

Tn hm javascript c gn vo s kin click tab pha client Phn chui hin th trn tab Mt TemplateInstance.Single Itemplate c dng cho tiu Mt TemplateInstance.Single Itemplate c dng cho ni dung

Th d: <ajaxToolkit:TabContainer runat=server OnClientActiveTabChanged=ClientFunction Height=110px> <ajaxToolkit:TabPanel runat=server HeaderText=Signature and Bio <ContentTemplate> </ContentTemplate> /> </ajaxToolkit:TabContainer> 11.6.29 TextBoxWatermark Control TextBoxWatermark l mt ASP.NET AJAX extender c th c gn vo mt TextBox trong ASP.NET c c hnh vi "watermark". Khi mt watermarked TextBox rng, n s hin th mt thng ip ti ngi dng vi kiu c ty chnh bi CSS. Mt khi ngi dng g mt s k t vo TextBox, watermarked s khng xut hin na. Mc ch chnh ca mt watermark l cung cp thm thng tin cho ngi s dng v cc TextBox m khng gy nn s xo trng ln phn cn li ca trang. Thuc tnh : Tn M t TargetControlID ID ca textbox WatermarkText Phn chui hin th khi textbox khng c ni dung WatermarkCssClass Lp css c p dng cho textbox khi n khng c ni dung Th d: <ajaxToolkit:TextBoxWatermarkExtender ID="TBWE2" runat="server" TargetControlID="TextBox1" WatermarkText="Type First Name Here" WatermarkCssClass="watermarked" />

Lu hnh ni b

Trang 381

BI THC HNH CHNG 11: Mt s th d vi Ajax Toolkit 3.5 Khi s dng AjaxToolkit th phi khai bo ScriptManager hoc l ToolkitScriptManager
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <asp:ToolkitScriptManager ID="ScriptManager1" runat="server"> </asp:ToolkitScriptManager>

1. Accordion Control Accordion control gip bn nh ngha nhiu lp v trnh by chng tng ci mt.N ging nh l c nhiu CollapsiblePanel controls m ch c mt ci c th m rng ti mt thi im.Accordion control cha mt hoc nhiu AccordionPane controls.Mi AccordionPane control c mt mu cho phn header v phn content ca n. 1.1. bc 1: ko th Accordion Control v to cc AccordionPane.
<asp:Accordion ID="Accordion1" CssClass="accordion" HeaderCssClass="accordionHeader" HeaderSelectedCssClass="accordionHeaderSelected" ContentCssClass="accordionContent" runat="server"> <Panes> <asp:AccordionPane ID="AccordionPane1" runat="server"> <Header>Pane 1</Header> <Content> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada

Lu hnh ni b

Trang 382

libero, sit amet commodo magna eros quis urna. </Content> </asp:AccordionPane> <asp:AccordionPane ID="AccordionPane2" runat="server"> <Header>Pane 2</Header> <Content> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci. </Content> </asp:AccordionPane> <asp:AccordionPane ID="AccordionPane3" runat="server"> <Header>Pane 3</Header> <Content> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci. </Content> </asp:AccordionPane> </Panes> </asp:Accordion>

1.2. bc 2 : to CSS cho ni dung trong AccordionPane


<style type="text/css"> .accordion { width: 400px; } .accordionHeader { border: 1px solid #2F4F4F; color: white; background-color: #2E4d7B; font-family: Arial, Sans-Serif; font-size: 12px; font-weight: bold; padding: 5px; margin-top: 5px; cursor: pointer; } .accordionHeaderSelected { border: 1px solid #2F4F4F; color: white; background-color: #5078B3; font-family: Arial, Sans-Serif; font-size: 12px; font-weight: bold; padding: 5px;

Lu hnh ni b

Trang 383

margin-top: 5px; cursor: pointer; } .accordionContent { background-color: #D3DEEF; border: 1px dashed #2F4F4F; border-top: none; padding: 5px; padding-top: 10px; } </style>

Kt qu:

2. AlwaysVisible Control L mt extender c dng hin th mt cch lin tc n mt iu khin ASP.NET.iu khin c m rng s lun lun di chuyn n mt v tr c nh trn trang bt k trang th thay i kch thc hay b cun. 2.1. Bc 1: ko th mt Panel:
<asp:Panel ID="Panel1" runat="server" CssClass="staticPanel"> <h2> Hello Words!!!</h2> </asp:Panel>

2.2. Bc 2: trong phn design, t Panel trn chn Add Extender, chn AlwaysVisibleControlExtender. Ta c on code nh sau: Lu hnh ni b Trang 384

<asp:AlwaysVisibleControlExtender
ID="Panel1_AlwaysVisibleControlExtender" runat="server" Enabled="True" VerticalSide="Middle" VerticalOffset="20" HorizontalSide="Center" HorizontalOffset="20" TargetControlID="Panel1"> </asp:AlwaysVisibleControlExtender>

2.3. Bc 3: to ni dung bn trong trang thy r chc nng ca Control ny. 2.4. Bc 4: to CSS cho Panel:
<style type="text/css"> .staticPanel { width: 110px; background-color: White; border: solid 1px black; padding: 10px; } </style>

Kt qu:

3. Animation Control: Phn m rng c s dng to cc hiu ng cho iu khin khi xy ra s kin. 3.1. Bc 1: to mt Panel, l i tng hin th Animation. Lu hnh ni b Trang 385

<asp:Panel ID="Message" runat="server"> Pay attention to me! </asp:Panel>

3.2. Bc 2: to mt LinkButton thc hin Animation.


<asp:LinkButton ID="lnkYellowFade" OnClientClick="return false;" runat="server">Play Animation</asp:LinkButton>

3.3. Bc 3: t LinkButton Add Extender, chn AnimationExtender.


<asp:AnimationExtender ID="lnkYellowFade_AnimationExtender" runat="server" Enabled="True" TargetControlID="lnkYellowFade"> <Animations> <OnClick> <Sequence> <Color AnimationTarget="Message" PropertyKey="backgroundColor" StartValue="#FFEF66" EndValue="#FFFFFF" /> </Sequence> </OnClick> </Animations> </asp:AnimationExtender>

Duration="2"

Property="style"

Trong th AnimationExtender to cc Animation. Bn trong l chc nng Click ca LinkButton. 3.4. Bc 4: to CSS cho Panel.
<style type="text/css"> #Message { width: 250px; padding: 10px; margin-bottom:10px; </style>

Kt qu:

Lu hnh ni b

Trang 386

4. ColorPicker Control Phn m rng ColorPicker cho php bn hin th mt bng pop-up mu khi con tr di chuyn n phn t input.Bn c th gn ColorPicker vo bt c textbox no ca ASP.NET.N cung cp mt hm cho php la chn mu pha client vi giao din ngi dng.Ngoi ra,bn c th ch ra mt button hin th mt popup la chn mu v mt iu khin cho php xem trc mu t bng mu.Bn c th cung cp mt textbox khi m ngi dng nhp vo mt gi tr mu th ColorPicker c th hin th mu tng ng nu mu khng c trong bng mu mc nh. 4.1. Bc 1: ko th mt TextBox <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 4.2. Bc 2: t TextBox AddExtender:
<asp:ColorPickerExtender ID="TextBox1_ColorPickerExtender" runat="server" Enabled="True" TargetControlID="TextBox1"> </asp:ColorPickerExtender>

Kt qu:

5. ComboBox Control. ComboBox l mt iu khin ca ASP.NET AJAX ,n ging nh AutoCompleteExtender,kt hp linh hot vi mt Textbox vi mt danh sch ty chn cho php ngi dng c th la chn.N c cc thuc tnh,hnh vi hay quy c t tn tng t nh trn Form combobox,v c cng lp c s nh l ListBox,BulletedList v DropDownList ca web control.Tht vy,ComboBox c xem nh l DropDownList nhng li c th g trc tip vo nh l textbox. 5.1. Bc 1: ko th mt ComboBox vi cc ListItem.
<asp:ComboBox ID="ComboBox1" runat="server"> <asp:ListItem Value="0">Cao</asp:ListItem> <asp:ListItem Value="1">Trung Binh</asp:ListItem> <asp:ListItem Value="2">Thap</asp:ListItem>

Lu hnh ni b

Trang 387

</asp:ComboBox>

5.2. Bc 2: to mt Button v mt Label hin th ni dung trong ComboBox c chn.


<asp:Button ID="btnSubmit" Text="Submit" Runat="server" OnClick="btnSubmit_Click"/> <br /> <br /> <asp:Label ID="lblSelection" Runat="server" />

5.3. To mt Script l Button_Click. <script runat="server"> public void btnSubmit_Click(object sender, EventArgs e) { lblSelection.Text = "You picked " + ComboBox1.SelectedItem.Text; } </script> Kt qu:

6. PopupCalendar Control. iu khin Calendar extender c th c gn vi bt k iu khin textbox no ca ASP.NET.N cung cp hm nh dng ngy pha client vi nh dng ngy ty bin vi giao din trong mt iu khin popup.Bn c th tng tc vi calendar bng cch click vo mt ngy chn,hoc Today chn ngy hin ti.Ngoi ra,mi tn tri phi c th c s dng chuyn ti thng trc hoc thng sau.Bng cch click vo tiu ca calendar bn c th thay i hin th ca cc ngy trong thng hin ti thnh cc thng trong nm hin ti.Click khc s chuyn cc nm trong thp k hin ti.Hnh ng ny cho php bn d dng chuyn n mt ngy trong qu kh hoc tng lai t iu khin calendar. 6.1. Bc 1: to mt TextBox. <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 6.2. Bc 2: t TextBox to trn Add Extender l CalendarExtender Lu hnh ni b Trang 388

<asp:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" Enabled="True" TargetControlID="TextBox1"> </asp:CalendarExtender> Kt qu:

7. AsyncFileUpload Control. AsyncFileUpload cho php bn upload file ln server mt cch bt ng b,kt qu ca file upload c th c kim tra c pha server ln client,bn c th lu file c upload bng cch gi phng thc SaveAs() trong iu khin s kin UploadedComplete server. 7.1. Bc 1: to mt AsyncFileUpload
<ajaxToolkit:AsyncFileUpload ID="AsyncFileUpload1" Width="400px" runat="server" OnClientUploadError="uploadError" OnClientUploadStarted="StartUpload" OnClientUploadComplete="UploadComplete" CompleteBackColor="Lime" UploaderStyle="Modern" ErrorBackColor="Red" ThrobberID="Throbber" onuploadedcomplete="AsyncFileUpload1_UploadedComplete" UploadingBackColor="#66CCFF" />

7.2. Bc 2: to mt Label th hin mt Image khi ang upload.


<asp:Label ID="Throbber" runat="server" Style="display: none"> <img src="Images/indicator.gif" align="absmiddle" alt="loading" /> </asp:Label>

Lu hnh ni b

Trang 389

7.3. a cc Script.
<script type="text/javascript"> function uploadError(sender, args) { document.getElementById('lblStatus').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>"; } function StartUpload(sender, args) { document.getElementById('lblStatus').innerText = 'Uploading Started.'; } function UploadComplete(sender, args) { var filename = args.get_fileName(); var contentType = args.get_contentType(); var text = "Size of " + filename + " is " + args.get_length() + " bytes"; if (contentType.length > 0) { text += " and content type is '" + contentType + "'."; } document.getElementById('lblStatus').innerText = text; } </script>

Kt qu:

8. DragPanelExtender DragPanel extender cho php ngi dng d dng thm mt phn c th ko i c trong iu khin ca h.DragPanel iu khin bt k panel no ca ASP.Net v thm mt tham s ni ln iu khin c dng nh l c th ko i c.Khi c khi to,ngi dng c th thoi mi ko panel quanh trang web s dng extender ny. 8.1. Bc 1: to Panel.
<asp:Panel ID="PnlContainer" runat="server" cssclass="dragContainer"> <asp:Panel ID="PnlHeader" runat="server" CssClass="dragHeader"> Click and Drag Here To Move ME.....around the page</asp:Panel> <asp:Panel ID="PnlDetail" runat="server" CssClass="dragDetail"> Here is just some content where you can add as much text as you like<br /> line 1<br /> line 2<br /> Remmeber that you can add any html text here<br /><br /> </asp:Panel>

Lu hnh ni b

Trang 390

</asp:Panel>

8.2. Bc 2: to mt DragPanelExtender
<asp:DragPanelExtender ID="PnlContainer_DragPanelExtender" runat="server" DragHandleID="PnlHeader" Enabled="True" TargetControlID="PnlContainer"> </asp:DragPanelExtender>

8.3. Bc 3: to CSS cho cc ni dung bn trong trang.


<style type="text/css"> .dragContainer{ background-color: #FFC0FF; height: 282px; width: 357px; border-bottom-color: black; } .dragHeader{ background-color: #8080FF; height: 48px; width: 358px; } .dragDetail{ background-color: #FFC0FF; height: 213px; width: 357px; } </style>

8.4. Bc 4: Script
<script type="text/javascript"> function setBodyHeightToContentHeight() { document.body.style.height = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight) + "px"; } setBodyHeightToContentHeight(); </script>

Kt qu:

Lu hnh ni b

Trang 391

9. DropShaDown 9.1. Bc 1: to mt Panel.


<asp:Panel ID="Panel1" runat="server" BackColor="Yellow" ForeColor="Black" Width="200px" > <br /><br /> <center> THIS is my content <br /> <br /> </center> </asp:Panel>

9.2. Bc 2: a vo mt DropShadowExtender cho Panel trn.


<asp:DropShadowExtender ID="Panel1_DropShadowExtender" runat="server" Enabled="True" TargetControlID="Panel1" Opacity="0.25" Rounded="true" Radius="11" TrackPosition="true" Width="25"> </asp:DropShadowExtender>

Kt qu:

Lu hnh ni b

Trang 392

10. DynamicPopulateExtender DynamicPopulate l mt extender n gin thay th ni dung ca mt control vi mt kt qu ca web service hay phng thc c gi.Phng thc c gi tr v mt chui HTML t vo phn t ch. 10.1. Bc 1: to mt Panel. <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br/>

10.2.

Bc 2: a vo mt DynamicPopulateExtender cho Panel trn.

<asp:DynamicPopulateExtender ID="Label1_DynamicPopulateExtender" runat="server" Enabled="True" PopulateTriggerControlID="" TargetControlID="Label1" BehaviorID="dp1" ClearContentsDuringUpdate="true" ServiceMethod="GetHtml" > </asp:DynamicPopulateExtender>

10.3.

Bc 3: to 2 radio button la chn.


value='radio 1'

<input type="radio" name="rbFormat" id="r0" onclick="updateDateKey(this.value);" checked="checked" />click to set 'radio 1'<br/> <input type="radio" name="rbFormat" id="Radio1" onclick="updateDateKey(this.value);" value='radio 2' />click to set 'radio 2'

10.4.

Script.

<script type="text/javascript"> function updateDateKey(value) { var behavior = $find('dp1'); if (behavior) { behavior.populate(value); } }

Lu hnh ni b

Trang 393

Sys.Application.add_load(function () { updateDateKey('radio 1 radio 2'); }); </script>

10.5. CodeBehind [System.Web.Services.WebMethod] [System.Web.Script.Services.ScriptMethod] public static string GetHtml(string contextKey) { System.Threading.Thread.Sleep(350); return String.Format("Persona: {0}", contextKey); } Kt qu:

11. HoverMenuExtender 11.1. Bc 1: to mt GridView v a HoverMenuExtender vo trong Column.


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" BorderColor="#628BD7" BorderStyle="Solid" BorderWidth="2px"> <Columns> <asp:BoundField DataField="ProductID" HeaderText="Product ID" /> <asp:BoundField DataField="ProductName" HeaderText="Product Name" /> <asp:BoundField DataField="UnitPrice" HeaderText="Unit Price" /> <asp:TemplateField HeaderText="Picture"> <ItemTemplate> <asp:Image runat="server" ID="thumbnailImage" ImageUrl='<%# Eval("Picture") %>' Width="70" Height="60" /> <asp:HoverMenuExtender ID="HoverMenuExtender1" runat="server" PopupControlID="popupImage" TargetControlID="thumbnailImage" OffsetX="10" OffsetY="5" PopupPosition="Right" PopDelay="100" HoverDelay="100"> </asp:HoverMenuExtender> <asp:Panel runat="server" ID="popupImage" BorderColor="#628BD7"

Lu hnh ni b

Trang 394

BorderStyle="Solid" BorderWidth="7px"> <asp:Image runat="server" ID="mainImage" ImageUrl='<%# Eval("Picture") %>' /> </asp:Panel> </ItemTemplate> </asp:TemplateField> </Columns> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> </asp:GridView>

11.2.

Bc 2: CodeBehind

protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { LoadData(); } } private void LoadData() { DataClasses1DataContext db = new DataClasses1DataContext(); var table = from t in db.Products select t; GridView1.DataSource = table; GridView1.DataBind(); }

Kt qu:

Lu hnh ni b

Trang 395

Chng 12:

Lp Trnh LINQ

Kt thc chng ny cc bn c th : Trnh by c kin trc ca LINQ . Trnh by c cc khi nim c bn trong LINQ M t v thc thi c LINQ to SQL M t v thc thi c LINQ to Object M t v thc thi LINQ to DataSet 12.1 Gii Thiu LINQ Cng ngh LINQ (Language Integrated Query) l gii php lp trnh hp nht em n kh nng truy vn d liu theo c php SQL trc tip trong C# hay VB.NET, p dng cho tt c cc dng d liu t i tng n CSDL quan h v XML. X l thng tin hay d liu l nhim v quan trng nht ca bt k phn mm no v mt trong nhng tr ngi chnh m cc nh pht trin hin nay phi i mt l khc bit gia ngn ng lp trnh hng i tng v ngn ng truy vn d liu, vn cng phc tp hn vi s xut hin ca XML (eXtensible Markup Language - ngn ng nh du m rng). Hin ti, cch ph bin nht ng dng ly d liu t cc h c s d liu (CSDL) l s dng SQL (Structure Query Language - ngn ng truy vn cu trc). SQL c c php rt khc vi nhng ngn ng lp trnh ph bin nh C# v VB.NET, do vy ngi lp trnh mt nhiu thi gian s dng hai thc th khc bit ny vi nhau trong mi d n phn mm. Mt vn khc vi SQL l n ch dng truy vn d liu trong cc CSDL dng quan h. Nu mun truy cp d liu XML hay dng khc (nh trang HTML, email...), nh pht trin li phi s dng c php truy vn khc (XPath/XQuery). gim gnh nng thao tc trn nhiu ngn ng khc nhau v ci thin nng sut lp trnh, Microsoft pht trin gii php tch hp d liu LINQ cho .NET Framework, y l th vin m rng cho cc ngn ng lp trnh C# v Visual Basic.NET (c th m rng cho cc ngn ng khc) cung cp kh nng truy vn trc tip d liu i tng, CSDL v XML. truy vn d liu i tng trong b nh , d liu cn phi vo b nh x l, nhng mt khi tch khi ni gc ca n th kh nng truy vn rt km. Bn c th d dng truy vn thng tin khch hng mc ni vi thng tin n hng ca h t CSDL SQL Server nhng khng d g thc hin tng t vi thng tin trong b nh. Trong mi trng .NET, thng tin (trong b nh) thng c th hin dng cc i tng v trc LINQ, khng c cch no mc ni cc i tng hay thc hin bt k thao tc truy vn no. LINQ chnh l gii php cho vn ny. Vi Microsoft .NET platform, ngn ng h tr chnh chnh l C# v VB.NET. Nhng ngi lp trnh vin h thng gp rc ri, v cm thy kh chu vi vic truy cp d liu nhng ngun khc nhau. c bit l 2 loi d liu XML v CSDL.Vi CSDL l mnh nht v d liu lu tr. Cc vn v truy xut d liu nh sau: Chng ta khng lp trnh tng tc vi CSDL ti cp native language. V th li thng kh pht hin r. Kh khn trong vic qun l li xy ra. Kiu d liu khc nhau trong mi ngun d liu XML v CSDL. c bit date v time.

Lu hnh ni b

Trang 396

Cc nh pht trin Microsoft a ra LINQ l 1 nn tng mi trong vic truy vn d liu bt k cc ngun khc nhau(Object, XML, CSDL). y l cng ngh m h tr c ch truy vn d liu tt c cc kiu. Nhng kiu nay bao gm mng (List, Vector), XML, CSDL... iu quan trng nht, LINQ l tt c v truy vn, kt qu sau khi truy vn c th l tp hp cc i tng cng loi, c th l 1 i tng n, c th l tp hp con ca cc trng (field) t 1 i tng. Kt qu tr v ca LINQ ngi ta gi l sequence. Hu ht sequence l IEnumerable<T> vi T l kiu d liu ca nhng i tng trong sequence. LINQ n s cung cp cch duy nht truy cp d liu t bt k ngun d liu no vi c php ging nhau.

Hnh 12.1 Kin trc LINQ

Hnh 12.2 Mt s tnh nng mi trong C# 3.0 s dng cho LINQ

Lu hnh ni b

Trang 397

Hnh 12.3 Minh ha ngn ng LINQ 12.2 Cc Khi Nim C Bn Extension Methods : L mt phng thc tnh ca mt lp tnh m chng ta c th t mt th hin ca phng thc trong mt lp khc.

Lu hnh ni b

Trang 398

Kt qu thi hnh

Automatic Properties Thng thng chng ta phi khai bo 1 lp v khai bo cc thnh phn d liu sau khai bo properties truy cp cc thnh phn ny.

Automatic Properties pht sinh t ng pht sinh cc thnh phn d liu khi chng ta khai bo properties.

Lu hnh ni b

Trang 399

Kt qu thi hnh

Lu hnh ni b

Trang 400

Object Initialization Object initialization cho php chng ta khi to cc gi tr cho cc thnh phn public v cc properties ca lp trong sut qu trnh khi dng.

Kt qu thi hnh

Anonymous Types Anonymous Types l kiu khng tn c pht sinh khi bin dch da vo qu trnh khi dng ca i tng ang c khi dng v khng th tr v t mt phng thc , ch c s dng nh l bin tham chiu cc b.

Lu hnh ni b

Trang 401

Kt qu thi hnh

Lambda Expressions Biu thc lambda c ch nh nh l cc tham s c phn cch bi du , theo sau l ton t lambda => hoc mt biu thc hoc mt khi lnh. C php : (param1, param2, paramN) => expr hay : (param1, param2, paramN) => { statement1; statement2; statementN; return(lambda_expression_return_type); }

Lu hnh ni b

Trang 402

Kt qu thi hnh

Query Expressions Biu thc Query cho php chng ta vit lnh truy vn trong LINQ gn ging vi cc lnh truy vn trong T-SQL C php : from itemName in srcExpr join itemName in srcExpr on keyExpr equals keyExpr (into itemName)? let itemName = selExpr where predExpr orderby (keyExpr (ascending | descending)?)* select selExpr group selExpr by keyExpr into itemName query-body

Lu hnh ni b

Trang 403

Kt qu thi hnh

12.3 LINQ to Objects LINQ to Object dng truy vn, sp xp ,lc d liu trong cc i tng nh : mng , tp hp

Hnh 12.4 Minh ha ngn ng LINQ to Objects. Lu hnh ni b Trang 404

Th d . minh ha s dng LINQ to Object chuyn 1 mng cc chui s sang 1 mng cc s nguyn.

Kt qu thi hnh

12.4 LINQ to DataSet LINQ to DataSet dng thc hin truy vn, sp xp , lc d liu,... nhanh v d dng hn trong i tng DataSet v cho php cc bn vit cc cu lnh truy vn trong ngn ng lp trnh thay v phi vit bng T-SQL . LINQ to DataSet cng c s dng truy vn d liu t mt hoc nhiu ngun d liu vi nhau.

Hnh 12.5 Minh ha ngn ng LINQ to DataSets. Lu hnh ni b Trang 405

Th d. Minh ha lc d liu vi LINQ to DataSet. To 1 trang ASP.Net hin th danh sch loi mt hng v cho php ngi dng lc danh sch ny theo tn loi mt hng. Bc 1 : Thit k giao din

Thuc tnh Gi tr thit lp ID gvDanhSachLoaiMatHang ID txtTenLoaiMatHang ID btnHienThiDanhSach Bng m t danh sch cc control Bc 2 . Vit lnh x l s kin.

Loi Control GridView TextBox Button

Lu hnh ni b

Trang 406

Bc 3 .Nhn Ctrl+F5 thi hnh ng dng . Kt qu nh sau

Lu hnh ni b

Trang 407

Nhp vo tn loi mt hng n , nhn nt Hin th danh sch xem danh sch cc loi hng m tn c cha chui n, kt qu lc d liu nh sau .

12.5 LINQ to SQL Trong LINQ to SQL , mt m hnh c s d liu quan h c nh x thnh mt m hnh i tng c thit k c bit trong ngn ng lp trnh. Khi ng dng thi hnh LINQ to SQL bin dch thnh ngn ng truy vn tch hp SQL trong m hnh i tng v gi n c s d liu thc thi, n khi c s d liu tr v kt qu , LINQ to SQL chuyn kt qu v li cc i tng cc bn c th thao tc trong ngn ng lp trnh.

Hnh 12.6 Minh ha ngn ng LINQ

Lu hnh ni b

Trang 408

Hnh 12.7M hnh hat ng ca LINQ to SQL Th d . To 1 trang ASP.Net dng xem, thm, xa, sa danh sch cc loi mt hng s dng LINQ to SQL. Bc 1 . Thit k giao din

Lu hnh ni b

Trang 409

Bc 2. To DataConnection kt ni vi c s d liu MinhHoa Trn thanh cng c Server Explorer | Data Connection, nhn phi chut chn Add New Connection.

Thc hin cc bc nh hnh sau v nhn nt OK hon tt to DataConnection

Bc 3 . To Data Context s dng LINQ to SQL kt ni vi bng LoaiMatHang ca c s d liu MinhHoa Lu hnh ni b Trang 410

Vo menu Project | Add New Items , chn LINQ to SQL Classes nh hnh sau :

Trn Server Explorer chn bng LoaiMatHang ko th vo MinhHoa.dbml

Bc 4. Vit lnh x l s kin. using System; using System.Collections.Generic; Lu hnh ni b Trang 411

using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace MinhHoa { public partial class MinhHoaLINQtoSQL : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { LayDanhSachLoaiMatHang(); } } public void LayDanhSachLoaiMatHang() { MinhHoaDataContext MinhHoaDC = new MinhHoaDataContext(); gvLoaiMatHang.DataKeyNames = new string[] { "MaLoaiMatHang" }; gvLoaiMatHang.DataSource = MinhHoaDC.LoaiMatHangs; gvLoaiMatHang.DataBind(); } protected void btnThem_Click(object sender, EventArgs e) { MinhHoaDataContext MinhHoaDC = new MinhHoaDataContext(); LoaiMatHang objLoaiMatHang = new LoaiMatHang { MaLoaiMatHang=int.Parse(txtMaLoaiMatHang.Text), TenLoaiMatHang = txtTenLoaiMatHang.Text, XuatXu = txtXuatXu.Text }; MinhHoaDC.LoaiMatHangs.InsertOnSubmit(objLoaiMatHang); MinhHoaDC.SubmitChanges(); LayDanhSachLoaiMatHang(); } protected void gvLoaiMatHang_PageIndexChanging(object sender, GridViewPageEventArgs e) { gvLoaiMatHang.PageIndex = e.NewPageIndex; Lu hnh ni b Trang 412

LayDanhSachLoaiMatHang(); } protected void gvLoaiMatHang_RowUpdating(object sender, GridViewUpdateEventArgs e) { //Lay cc gi tr thay i t ngi dng TextBox txtTenLoaiMatHang = gvLoaiMatHang.Rows[e.RowIndex].Cells[1].Controls[0] as TextBox; TextBox txtXuatXu = gvLoaiMatHang.Rows[e.RowIndex].Cells[2].Controls[0] as TextBox; int MaLoaiMatHang = (int)gvLoaiMatHang.DataKeys[e.RowIndex].Value; MinhHoaDataContext MinhHoaDC = new MinhHoaDataContext(); LoaiMatHang lmh = MinhHoaDC.LoaiMatHangs.SingleOrDefault (loaihang => loaihang.MaLoaiMatHang == MaLoaiMatHang); lmh.MaLoaiMatHang = MaLoaiMatHang; lmh.TenLoaiMatHang = txtTenLoaiMatHang.Text; lmh.XuatXu = txtXuatXu.Text; MinhHoaDC.SubmitChanges(); gvLoaiMatHang.EditIndex = -1; LayDanhSachLoaiMatHang(); } protected void gvLoaiMatHang_RowDeleting(object sender, GridViewDeleteEventArgs e) { int MaLoaiMatHang = (int)gvLoaiMatHang.DataKeys[e.RowIndex].Value; MinhHoaDataContext MinhHoaDC = new MinhHoaDataContext(); LoaiMatHang lmh = MinhHoaDC.LoaiMatHangs.SingleOrDefault (loaihang => loaihang.MaLoaiMatHang == MaLoaiMatHang); MinhHoaDC.LoaiMatHangs.DeleteOnSubmit(lmh); MinhHoaDC.SubmitChanges(); LayDanhSachLoaiMatHang(); } protected void gvLoaiMatHang_RowEditing(object sender, GridViewEditEventArgs e) { gvLoaiMatHang.EditIndex = e.NewEditIndex; Lu hnh ni b Trang 413

LayDanhSachLoaiMatHang(); } protected void gvLoaiMatHang_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { gvLoaiMatHang.EditIndex = -1; LayDanhSachLoaiMatHang(); } } } Bc 5 . Thi hnh ng dng v thc cc chc nng tng ng . Kt qu nh hnh sau.

Lu hnh ni b

Trang 414

Chng 13:

Lp trnh WebServices

Kt thc chng ny cc bn c th : Trnh by c cc khi nim ca WebService M t c cc thnh phn trong WebService. Xy dng c ng dng WebService 13.1. Web services Mt dch v web (web services) l mt h thng phn mm c xy dng h tr kh nng tng tc gia cc my tnh trn mng (theo Wide Web Consortium). N cung cp mt giao tip c m t theo mt nh dng chung thng gi l ngn ng m t dch v web (Web Service Description Language WSDL). Cc h thng khc thc hin tng tc vi dch v web thng qua giao thc SOAP (Simple Object Access Protocol). y l giao thc gip trao i thng tin s dng HTTP kt hp vi vic s dng c t XML cng vi mt s chun khc. Nh vy, mc ch chnh ca vic pht trin ca dch v web l cho php giao tip v trao i cc chc nng, thng tin, d liu gia cc ng dng mt cch d dng m khng cn quan tm n mi trng pht trin, ngn ng lp trnh bi tt c c quy v mt nh dng chung. Bn cht ca web service l mt tp hp cc i tng, cc phng thc c thc thi v cng b trn mng c th c triu gi t xa thng qua cc ng dng khc. xem xt k hn v web service, chng ta s tm hiu s ra i v vai tr ca web service. 13.1.1. S ra i ca web services Web service l s k tha t cc cng ngh phn tn trc nh CORBA, DCOM v RMI CORBA (Common Object Request Broker Architecture)Error! Reference source not found.Error! Reference source not found.Error! Reference source not found.Error! Reference source not found. l mt gii php da trn cc chun m do t chc OMG (Object Management Group) a ra. im mnh ca CORBA l cc ng dng trn my client v trn my ch c th c vit bng cc ngn ng lp trnh khc nhau nh s dng mt ngn ng nh ngha giao tip (Interface Definition Language IDL)Error! Reference source not found.. Tuy nhin, vic xy dng ng dng phn tn s dng CORBA rt phc tp v c rt t ngn ng lp trnh c CORBA h tr. DCOM (Distributed Component Object Model)Error! Reference source not found.Error! Reference source not found.Error! Reference source not found. c xut bi Microsoft, gip cc thnh phn phn mm (software component) giao tip vi nhau trn mi trng phn tn. Mt DCOM server s cng b cc phng thc, cc i tng cho cc my khch bng cch h tr a giao tip (multiple interfaces). Giao thc c s dng cho vic giao tip gia cc ng dng l Object Remote Procedure Call (ORPC). DCOM ch yu c pht trin trn cc h iu hnh Windows v ch yu c h tr pht trin bi MicrosoftError! Reference source not found.. RMI (Remote Method Invocation RMI) Error! Reference source not found.Error! Reference source not found.Error! Reference source not found.Error! Reference source not found.cho php xy dng cc ng dng phn tn da trn cng ngh Java. Mt i tng vit bng Java c th gi n mt i tng t xa m n tham chiu n. RMI s dng giao thc JRMP (Java Remote Method Protocol). xy dng mt ng dng phn tn s dng RMI i hi ngi lp trnh phi c kin thc, kinh nghim v lp trnh vi ngn ng Java v k thut phn tn. Mc khc, hn ch ln nht ca RMI l ch h tr i vi cc ng dng JavaError! Reference source not found.. Lu hnh ni b Trang 415

Bn cnh nhng hn ch ca cc cng ngh ni trn, mt vn pht sinh y l kh nng tng tc gia cc ng dng c xy dng trn cc cng ngh khc nhau. Chng ta khng th giao tip vi mt server s dng cng ngh DCOM t mt ng dng s dng cng ngh RMI bi chng s dng hai giao thc khc nhau. V vy, web service ra i l mt s pht trin c vai tr quan trng trong lnh vc phn tn trn internet. 13.1.2. Vai tr v c im ca web services Web service ra i m ra mt hng mi cho vic pht trin cc ng dng trn internet. Ngy nay, dch v web c s dng trong nhiu lnh vc pht trin phn mm khc nhau nh cc dch v cung cp gi c phiu, h tr thanh ton trc tuyn, chuyn i ngoi t, tm kim thng tin lin quan n sn phm, c bit l cc dch v web ca cc website bn hng trc tuyn nh Amazon, eBay. Web service ng vai tr quan trng trong vic pht trin cc ng dng thng mi in t (e-commerce). Dng dch v web kt hp cc cc kh nng n l chy trn cc h thng khc nhau thnh mt h thng tch hp. 13.2. Kin trc v cc thnh phn Web services Cng ngh web service khng phi l mt cng ngh mi hon ton, m n ra i da trn s kt hp cc nn tng cng ngh sn c trc . N l s tch hp cc ng dng da trn web s dng cc chun m nh XML, SOAP, WSDL, UDDI. Trong , XML c s dng m t d liu, SOAP ng vai tr giao thc truyn ti d liu, WSDL m t cho dch v web v UDDI lit k danh sch cc dch v web ang hot ng. 13.2.1. XML Extensible Markup Language XML do W3C ra v c pht trin t SGML. XML l mt ngn ng nh du m rng vi cu trc do ngi dng nh ngha. V hnh thc, XML c c php tng t HTML, nhng khng tun theo mt c t quy c nh HTML. Ngi s dng hay cc chng trnh c th quy c nh dng cc th XML, ngoi ra khng cha bt c thng tin no khc v cch s dng hay hin th nhng thng tin y. Web service l s kt hp ca nhiu thnh phn khc nhau, v n h tr tng tc gia cc h thng c ci t trn cc mi trng khc nhau. Do , cn s dng mt dng ti liu c th gip gii quyt vn tng thch v XML hon ton ph hp vi yu cu trn. N tr thnh nn tng cho vic xy dng cc web service. XML c hai vai tr chnh: Trao i d liu trong h thng s dng web service. M t cc giao thc s dng trong dch v web. 13.2.2. SOAP Simple Object Access Protocol SOAP (Simple Object Access Protocol) l giao thc dng truy xut thng tin t web service thng qua mt dng thng ip chung. SOAP c Microsoft xut vo nm 1998. Hin nay, n thuc quyn qun l v ci tin bi t chc W3C. SOAP l mt giao thc da trn nn tng XML, m t cch nh dng, ng gi thng tin ca cc thng ip v trao i chng thng qua mng m khng ph thuc vo bt k ngn ng hay mi trng thc thi no. n v trao i thng tin c bn ca giao thc SOAP l thng ip SOAP (SOAP Message). Mi thng ip SOAP s c ch nh bi mt th root <Envelope> cha 2 thnh phn l SOAP Header v SOAP Body. SOA Header cha cc thng tin cn thit cho vic thc hin chuyn thng ip hay c ch nh danh, bo mt. SOAP Body cha d liu ng dng Cu trc ca mt thng ip SOAP nh hnh sau:

Lu hnh ni b

Trang 416

Hnh sau s m t cch m SOAP c s dng trong web services..

Lu hnh ni b

Trang 417

13.2.3. WSDL Web Services Description Language WSDL (Web Services Description Language) l mt dng ti liu da trn c php XML m t cc dch v web. Lc u n c Microsoft, IBM v Ariba xut, nhng hin nay c qun l bi t chc W3C. Mt ti liu WSDL s cung cp ti liu cho cc h thng phn tn nh m t chc nng ca mt web service, cch thc tng tc, cc thng ip tng ng cho cc theo tc request hay response. Sau y l cu trc c bn ca mt ti liu Mt ti liu WSDL bao gm 2 thnh phn chnh: Phn tru tng (abstract definitions)Error! Reference source not found., v phn hin thc (concrete definitions)Error! Reference source not found.. Phn tru tng bao gm cc thng tin c cha cc th types, message, operation, v port types. Phn hin thc cha thng tin trong cc th bindings v ports. Mi thnh phn s c mt tham chiu n mt thnh phn khc c m t nh hnh sau:

H n h 1 3 . 3 . W S

Lu hnh ni b

Trang 418

Hnh 13.4. Cc thnh phn ca WSDL Mi thnh phn c mt chc nng ring, c th nh sau: types: ch nh kiu d liu cho cc thng ip gi v nhn. messages: l mt thnh phn tru tng m t cch thc giao tip gia client v server porttypes: m t nh x gia cc thng ip c m t trong phn t messages v cc phng thc (operations). binding: xc nh giao thc no c s dng khi giao tip vi dch v web. nh ngha kiu binding (RPC/Document) v giao thc vn chuyn. binding cng nh ngha cc operations. Port: ch nh a ch hoc im kt ni n web service, n thng l mt chui URL n gin. 13.2.4. UDDI Universal Description, Discovery, and Integration UDDI (Universal Description, Discovery, and Integration) Error! Reference source not found.Error! Reference source not found.Error! Reference source not found.Error! Reference source not found. c xut bi Microsoft, IBM v Ariba vo nm 2000. Ngy nay, UDDI thuc quyn qun l v pht trin bi t chc OASIS (Organization for the Advancement of Structured Information Standards). N c xy dng nhm mc ch cung cp kh nng cho php cng b, tng hp v tm kim cc dch v web. UDDI a ra mt tp cc hm API c chia lm 2 phn: Inquiry API (dng tm kim v truy xut) v Publishers API (cng b cc web services). Thng tin t chc trong UDDI c chia thnh 3 phn: White pages: Lit k thng tin ca cc nh cung cp dch v web bao gm a ch, thng tin lin lc, v nh danh. Yellow pages: Phn loi dch v theo t chc hay nhm dch v hoc a im t cc dch v.

Lu hnh ni b

Trang 419

Green pages: Cung cp thng tin v cc dch v web c, v cch thc truy xut cc web services . 13.2.5 Kt lun Thng qua cc phn trn, chng ta c mt c ci nhn ton cnh v Web Service, cc k thut ct li ca vic p dng cc ng dng phn tn da vo SOAP, WSDL, v UDDI:

Cc nh cung cp Web Service s m t Web Sercive ca mnh trong mt ti liu WSDL v cng b thng qua vic ng k UDDI s dng Publishers API (da trn nn tng SOAP) Mt service requester s dng UDDI Inquiry API tm kim cc service provider tng ng vi yu cu bn trong h thng ng k UDDI. Nu c mt dch v no c tm thy, vic lm tip theo l da vo <tModel> tham chiu n ti liu WSDL tng ng. Mt SOAP request s c to ra tng ng vi Web Service c tm thy. Sau cng SOAP request s c gi n service provider, v provider x l tr v. 13. 3 Xy Dng ng Dng Web Service Bc 1 . To ng dng WebService T menu File | New | New WebSite...,ca s New Web Site xut hin v thit lp nh hnh di y to ng dng Web Service tn WS_MinhHoa s dng Web Server IIS.

Lu hnh ni b

Trang 420

Bc 2. Sau khi WS_MinhHoa c to , cc bn vit lnh trong tp tin App_Code/Service.cs nh sau . using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Service : System.Web.Services.WebService { public Service () { } [WebMethod] public string LayGioHienHanh() { return DateTime.Now.ToString("hh:mm:ss"); } } Trong webservice ny chng ta khai bo mt phng thc tn LayGioHienHanh dng ly gi hin hnh pha server. Bc 3 . Nhn Ctrl+F5 thi hnh ng dng , giao din thi hnh sau y lit k danh sch phng thc web hin c trong Web Service. Lu hnh ni b Trang 421

Nhp vo lin kt LayGioHienHanh gi phng thc ny.

Nhn nt Invoke thc thi phng thc LayGioHienHanh , kt qu nh mn hnh sau .

Lu hnh ni b

Trang 422

Kt qu tr v t phng thc LayGioHienHanh Bc 4 . To ng dng Web Consumer , cc bn c th s dng bt k ng dng no gi n Web Service ( ASP.Net. Window Form, Console ,...). Trong v d ny chng ta s dng ASP.Net. To ng dng ASP.Net , gm 1 trang tn LayGioHienHanh.aspx giao din nh sau :

Bc 5 .Thit lp tham chiu n ng dng web service WS_MinhHoa.

Lu hnh ni b

Trang 423

T ng dng ASP.Net , nhp chn References , nhp phi chut chn Add Web Reference...

Trn ca s Add Web Reference , nhp vo lin kt Web services on the local machine

Sau chn service nh hnh sau .

Lu hnh ni b

Trang 424

Lu hnh ni b

Trang 425

Nhn Add Reference thm tham chiu vo ng dng

Bc 6 . Vit lnh x l s kin trang LayGioHienHanh.aspx using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace MinhHoa { public partial class HienThiGioHienHanh : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnHienThi_Click(object sender, EventArgs e) { //khai bo i tng Service localhost.Service s = new localhost.Service(); //gi phng thc lbGioHienHanh.Text = s.LayGioHienHanh(); } } } Lu hnh ni b Trang 426

Bc 7 . Nhn Ctrl+F5 thi hnh trang LayGioHienHanh.aspx, sau nhn nt Hin th xem kt qu.

Lu hnh ni b

Trang 427

Chng 14:

XY DNG WEBSITE BN HNG

a. b.

c. d.

14.1 THNG MI IN T 14.1.1 Khi nim 14.1.1.1 Theo ngha hp Thng mi in t (E-Commerce hay E-Business) l hnh thi hot ng thng mi trong vic mua bn hng ha v dch v bng phng tin in t, nht l qua internet v cc mng lin thng khc. Theo T chc thng mi th gii (WTO) : Thng mi in t bao gm vic sn xut, qung co, bn hng v phn phi sn phm c mua bn v thanh ton trn mng internet, nhng c giao nhn mt cch hu hnh, c cc sn phm giao nhn cng nh nhng thng tin s ha thng qua mng internet.Error! Reference source not found. 14.1.1.2. Theo ngha rng Thng mi din t l cc giao dch ti chnh v thng mi bng phng tin in t nh: trao i d liu in t, chuyn tin in t v cc hot ng nh gi/rt tin bng th tn dng. Theo Lut mu v thng mi in t ca y ban Lin hp quc v Lut Thng mi quc t (UNCITRAL): Thut ng thng mi-Commerce- cn c din gii theo ngha rng bao qut cc vn pht sinh t mi quan h mang tnh cht thng mi d c hay khng c hp ng. Cc quan h mang tnh thng mi bao gm cc dch v sau y: bt c giao dch no v cung cp hoc trao i hng ha, dch v; tha thun phn phi; i din hoc i l thng mi, y thc hoa hng (factoring), cho thu di hn (leasing); xy dng cc cng trnh, t vn, k thut cng trnh (engineering); u t, cp vn, ngn hng, bo him; tha thun khai thc hoc t nhng, lin doanh v cc hnh thc khc v hp tc cng nghip hoc kinh doanh; chuyn ch hng ha hay hnh khch bng ng bin, ng hng khng, ng st hoc ng b.Error! Reference source not found. Nh vy, c th thy rng phm vi ca Thng mi in t rt rng, bao qut hu ht cc lnh vc hot ng kinh t. Trong , hot ng mua bn hng ha v dch v ch l mt phm vi rt nh trong Thng mi in t. Ngy nay, ngi ta hiu khi nim Thng mi in t thng thng l tt c cc phng php tin hnh kinh doanh v cc quy trnh qun tr thng qua cc knh in t, m trong internet hay t nht l cc k thut v giao thc c s dng trong internet ng mt vai tr c bn, v cng ngh thng tin c coi l iu kin tin quyt. 14.1.2. c trng So vi cc hot ng thng mi truyn thng, Thng mi in t c mt s im khc bit c bn sau: Cc bn tin hnh giao dch trong Thng mi in t khng tip xc trc tip vi nhau v khng i hi phi bit nhau t trc. Cc giao dch thng mi truyn thng c thc hin vi s tn ti ca khi nim bin gii quc gia, cn Thng mi in t c thc hin trong mt th trng khng c bin gii (th trng thng nht ton cu). Thng mi in t tc ng trc tip ti mi trng cnh tranh ton cu. Trong hot ng giao dch Thng mi in t u c s tham gia ca t nht ba ch th, trong c mt bn khng th thiu c l ngi cung cp dch v mng, cc c quan chng thc. i vi thng mi truyn thng th mng li thng tin ch l phng tin trao i d liu, cn vi Thng mi in t th mng li thng tin chnh l th trng. Lu hnh ni b Trang 428

14.1.3. Phn loi Trong thng mi in t c ba ch th tham gia: Doanh nghip (B) gi vai tr ng lc pht trin thng mi in t, Ngi tiu dng (C) gi vai tr quyt nh s thnh cng ca thng mi in t v Chnh ph (G) gi vai tr nh hng, iu tit v qun l. Theo tnh cht ca ngi tham gia, thng mi in t bao gm: Ngi tiu dng: o C2C (Consumer to Consumer): Ngi tiu dng vi ngi tiu dng. o C2B (Consumer to Business): Ngi tiu dng vi doanh nghip. o C2G (Consumer to Government): Ngi tiu dng vi Chnh ph. Doanh nghip: o B2C (Business to Consumer): Doanh nghip vi ngi tiu dng. o B2B (Business to Business): Doanh nghip vi doanh nghip. o B2G (Business to Government): Doanh nghip vi Chnh ph. o B2E (Business to Employee): Doanh nghip vi nhn vin. Chnh ph: o G2C (Government to Consumer): Chnh ph vi ngi tiu dng. o G2B (Government to Business): Chnh ph vi doanh nghip. o G2G (Government to Government): Chnh ph vi Chnh ph. Trong , B2B v B2C l hai loi hnh giao dch thng mi in t quan trng nht. B2B (Business to Business): l vic thc hin cc giao dch gia cc doanh nghip vi nhau trn mng. Cc bn tham gia giao dch gm: ngi trung gian trc tuyn, ngi mua v ngi bn. Cc loi giao dch gm: mua ngay theo yu cu khi gi c thch hp v mua theo hp ng di hn, da trn m phn c nhn gia ngi mua v ngi bn Error! Reference source not found.. Cc loi giao dch c bn: o Bn bn: (mt bn bn - nhiu bn mua) l m hnh da trn cng ngh web trong mt cng ty bn cho nhiu cng ty mua. C ba phng php bn trc tip trong m hnh ny: bn t Catalog in t, bn qua qu trnh u gi, bn theo hp ng cung ng di hn tha thun trc. o Bn mua: mt bn mua nhiu bn bn o Sn giao dch: nhiu bn bn nhiu bn mua o Thng mi in t phi hp: cc i tc phi hp nhau ngay trong qu trnh thit k, ch to sn phm. B2C (Business to Consumer): y l m hnh bn l trc tip n ngi tiu dng. Trong thng mi in t, bn l in t c th t nh sn xut hoc t mt ca hng thng qua knh phn phi. M hnh kinh doanh bn l c th phn loi theo quy m cc loi hng ha, theo phm vi a l (ton cu, khu vc) hoc theo knh bn (bn trc tip hoc qua knh phn phi) Error! Reference source not found.. Mt s hnh thc ca ca hng bn l trn mng: o Brick-and-mortar: l loi ca hng bn l kiu truyn thng, khng s dng internet. o Click-and-mortar: l loi ca hng bn l truyn thng nhng c knh bn hng qua mng o Ca hng o: l ca hng bn l hon ton trn mng m khng s dng knh bn truyn thng. 14.1.4. Cc hnh thc hot ng a. Th in t (email) Cc doanh nghip, ca hng kinh doanh s dng th in t gi th cho nhau hoc gi th qung b sn phm mt cch trc tuyn thng qua mng, gi l th in t (electronic Lu hnh ni b Trang 429

mail, vit tt l e-mail). Thng tin trong th in t khng phi tun theo mt cu trc nh trc no. b. Thanh ton in t Thanh ton in t (electronic payment) l vic thanh ton tin thng qua th in t (electronic message) nh tr lng bng cch chuyn tin trc tip vo ti khon, tr tin mua hng bng th tn dngNgy nay, vi s pht trin ca TMDT, thanh ton in t m rng sang cc lnh vc mi: Trao i d liu in t ti chnh (Financial Electronic Data Interchange, gi tt l FEDI): chuyn phc v cho vic thanh ton in t gia cc cng ty giao dch vi nhau bng in t. Tin l in t (Internet Cash): l tin mt c mua t ni pht hnh (ngn hng hoc mt t chc tn dng no ), sau c chuyn i t do sang cc ng tin khc thng qua internet, p dng trong c phm vi mt nc cng nh gia cc quc gia. V in t (Electronic Purse): l ni tin mt Internet, ch yu l th thng minh (smart card), cn gi l th gi tin (stored value card), tin c tr cho bt k ai c c th Giao dch in t ca ngn hng (Digital Banking) c. Trao i d liu in t Trao i d liu in t (Electronic Data Interchange, vit tt l EDI) l vic trao i cc d liu di dng c cu trc (structured form) t my tnh in t ny sang my tnh in t khc, gia cc cng ty hoc n v tha thun bun bn vi nhau. Ngy nay EDI ch yu c thc hin thng qua mng Internet. phc v cho bun bn gia cc doanh nghip thun li hn vi chi ph truyn thng khng qu tn km, ngi ta xy dng mt kiu mng mi gi l mng ring o (Virtual Private Network), l mng ring dng Intranet ca mt doanh nghip nhng c thit lp da trn chun trang Web v truyn thng qua mng Internet. Cng vic trao i EDI trong TMT thng gm cc ni dung sau: o Giao dch kt ni o t hng o Giao dch gi hng o Thanh ton d. Truyn dung liu (Content) Dung liu (Content) l ni dung ca hng ha s, gi tr ca n khng phi trong vt mang tin m nm trong bn thn ni dung ca n. Hng ha s c th giao qua mng, nh: tin tc, nhc, phim, cc chng trnh truyn hnh, cc chng trnh phn mm, v xem phim, v my bay e. Mua bn hng ha hu hnh n nay, danh sch cc hng ha bn l qua mng m rng, t hoa, qun o n t v xut hin mt loi hot ng gi l mua hng in t (electronic shoping) hay mua hng trn mng; mt s nc, internet bt u tr thnh cng c cnh tranh bn l hng hu hnh (Retail of tangible goods). Tn dng tnh nng a phng tin (multimedia) ca mi trng Web, ngi bn hng xy dng trn mng cc ca hng o (virtual shop), gi l o bi v, ca hng c tht nhng ta ch xem ton b quang cnh ca hng v cc hng ha cha trong trn tng mn hnh. 14.1.5. Li ch Sau y l mt s li ch m thng mi in t mang li: Thu thp c nhiu thng tin: gip doanh nghip thu thp thng tin phong ph v kinh t th trng, nh c th xy dng chin lc sn xut v kinh doanh thch hp vi xu th pht trin ca th trng trong nc v quc t. Lu hnh ni b Trang 430

Gim chi ph sn xut: trc ht l chi ph vn phng, chi ph tm kim chuyn giao ti liu v chi ph in. Gim chi ph bn hng, tip th v giao dch: bng phng tin internet/web mt nhn vin bn hng c th giao dch c vi rt nhiu khch hng, gip gim chi ph v thi gian giao dch. Xy dng quan h vi i tc: to iu kin cho vic thit lp v cng c mi quan h gia cc thnh vin tham gia vo qu trnh thng mi nh ngi tiu th, doanh nghip, c quan Chnh Ph Mi ngi c th giao tip trc tip v lin tc vi nhau, c cm gic nh khng c khong cch v a l v thi gian na. To iu kin sm tip cn vi kinh t tri thc: trc ht, thng mi in t s kch thch s pht trin ca cng ngh thng tin, to c s cho pht trin kinh t tri thc. 14.1.6. Kt Lun Phn ny gii thiu mt s l thuyt v thng mi in t nh khi nim, c trng, phn loi, cc hnh thc hot ng v li ch. 14.2 KHO ST HIN TRNG 14.2.1. nh gi mt s website thng mi in t ti Vit Nam v trn th gii c ci nhn tng qut v thng mi in t, chng ti kho st mt s website thng mi in t ni ting Vit Nam v trn th gii. Th gii: Thng mi in t nc ngoi nht l cc nc pht trin c t lu v hin nay pht trin vt bc. Do iu kin c s vt cht thun li, hu ht mi ngi dn u s dng internet v vic gi tin ngn hng l rt ph bin, nn thng mi in t c xem nh l s la chn hng u ca mi ngi. Thm vo , thng mi in t mang li nhiu li ch thit thc cho ngi s dng nh tit kim thi gian, tit kim tin bc v c cc phng thc thanh ton rt d dng, thun li v nhanh chng. T , s tin tng ca ngi dng vo vic la chn thng mi in t ngy cng tng v ngy cng thu ht mi ngi tham gia. Do , li nhun m thng mi in t mang li cho cc nc pht trin l khng nh. Mt s website thng mi in t ni ting nc ngoi: [1] http://www.ebay.com Trang web ny khng ch cho php ngi dng mua sn phm trc tip m cn cho h a sn phm ln bn cho cc khch hng khc. Ebay cho php khch hng la chn phng thc thanh ton sao cho tin li vi mnh nht. Mt s phng thc thanh ton m Ebay h tr l: thanh ton thng qua PayPal, ProPay, Paymate, Moneybookers v Credit Card hoc Debit Card. Trong , phng thc thanh ton ch yu dng hu ht cho ngi bn v ngi mua l thanh ton qua PayPal. Khch hng c th thanh ton bt k ni no trn th gii.

Lu hnh ni b

Trang 431

Hnh 26.1. Website www.ebay.com [2] http://www.amazon.com Trang web Amazon c mt im mi l cho php khch hng c th bn sn phm ca mnh trn chnh trang web thng mi in t ca khch hng (WebStore with Amazon). Amazon cng h tr nhiu phng thc thanh ton cho khch hng, sao cho c th mang li s tin li nht. Mt s phng thc thanh ton m Amazon h tr l: thanh ton trc tip t ti khon ngn hng ca khch hng, Amazon.com Store Card, Gift Cards, Credit Card v Check Card nh Visa, MasterCard/EuroCard, Discover Network, American Express, JCB, Amazon Credit Account.

Lu hnh ni b

Trang 432

Hnh 26.2. Website www.amazon.com Vit Nam: Nhn chung thng mi in t vn cn trong giai on th thch v c tim nng pht trin rt ln. Vit Nam, thng mi in t dng nh vn cn mi i vi mi ngi. Hin nay, thng mi in t ang dn dn khng nh v th v li ch ca mnh, thu ht ngy cng nhiu khch hng tham gia mua hng trc tuyn. Nhng do tm l ngi dn cha quen vi vic c mt ti khon ngn hng, cng nh ch mt s ngn hng c s h tr thanh ton trc tuyn, nn vic giao dch thng mi in t thng qua ngn hng vn cn hn ch. Cc website thng mi in t c nhng phng thc thanh ton ring cho mnh, nhm h tr ti a cho cc khch hng, v gip cc khch hng c th thc hin phng thc thanh ton n gin, tin dng v nhanh nht. Mt s website thng mi in t tiu biu: [1]. http://ebay.chodientu.vn website ny, khch hng c th la chn cc khu vc c h tr, l khu vc khch hng c th mua sn phm, khu vc khch hng c th bn sn phm ca mnh v cui cng l khu vc mua c bit, khi m sn phm khch hng cn mua khng c trn website. Ngoi ra, khch hng cn c th la chn mua hng bng hnh thc u gi hoc mua ngay. Trang web ny c hai phng thc thanh ton c h tr cho khch hng, l thng qua: Ti khon ti Ngn lng (http://www.nganluong.vn). Ti khon ti mt s ngn hng c h tr thanh ton trc tuyn nh Ngn hng ng , Ngn hng u t v pht trin Vit Nam, Ngn hng Ngoi thng Vit Nam

Lu hnh ni b

Trang 433

Hnh 26.3. Website ebay.chodientu.vn [2]. http://www.vinabook.com website ny, ch c th h tr khch hng mua sn phm m khng th bn sn phm mnh c thng qua trang web cho cc khch hng khc. B li, trang web c h tr nhiu phng thc thanh ton, c th thanh ton trong nc cng nh thanh ton quc t, gip khch hng c th la chn phng thc thanh ton ph hp vi mnh nht. Thanh ton trong nc o Thanh ton trc tip khi nhn hng o Chuyn tin qua bu in o Thanh ton bng th ATM o Thanh ton bng v in t Payoo o Thanh ton bng Vinapay: v in t Vcash o Th tr trc Vinabook Thanh ton quc t o Chuyn tin Western Union o Thanh ton bng Credit Card o Chuyn khon ngn hng

Lu hnh ni b

Trang 434

Hnh 26.4. Website www.vinabook.com 14.2.2. Cc yu cu nghip v ca website Xy dng ng dng s dng cng ngh web service vi cc yu cu sau: Xy dng website bn sch qua mng Tm kim v so snh sch ca website vi cc sn phm tng t trn cc website khc (amazon, ebay, ) Thc hin thanh ton trc tuyn ngay trn website T cc yu cu trn, web site phi m bo cc nghip v ch yu sau: Nghip v M t 1. ng k ti khon Cho php khch hng ng k ti thnh vin, tin cho nhng khch hng thng xuyn mua sn phm trn website 2. Tm kim sn phm c trong website Ngi dng c th tm kim sn phm mnh cn trn website 3. Tm kim sn phm website khc Chc nng ny cho php ngi dng tm sn phm trn cc website khc Amazon, Ebay ngi dng c th tham kho, mua hng t cc website . Lit k mt s thng tin lin quan n Trang 435

4. Xem thng tin sn phm Lu hnh ni b

5. Thanh ton trc tuyn

6. To gi hng

7. Cp nht, thm, xa sn phm trong gi hng 8. So snh sn phm

9. Thanh ton trc tuyn 10. Chuyn i tin t 11. Qun l user 12. Qun l ti khon 13. Thm, xa, sa sn phm ca website 14. Qun l cc n t hng

sn phm Cho php ngi dng thanh ton trc tuyn thng qua dch v thanh ton ca Paypal... Ngi dng s to cho mnh mt gi hng lu tr sn phm mnh cn mua. Cho php ngi dng thm, xa sn phm cn mua t gi hng. So snh sn phm ang xem vi cc sn phm tng t trn amazon, v ebay (nu c) Thanh ton thng qua dch v ca PayPal Chuyn i qua li gi ca sn phm gia cc loi tin t thng dng. Admin qun l ti khon ngi dng Ngi dng c th thay i mt s thng tin ng k. Cp nht sn phm ca website Xem chi tit, xc nhn, hoc hy b cc n t hng

Bng 26.1 . Cc nghip v ca Website 14.3. Kt lun Chng ny trnh by vn tt hin trng mt s website thng mi in t Vit Nam v trn th gii, qua xy dng cc yu cu nghip v ph hp cho website.

Lu hnh ni b

Trang 436

Chng 15 : THIT K WEBSITE BN HNG MC D LIU


Kin trc xy dng website bn sch qua mng c p dng webservices. Website s dng m hnh 3 lp (three-tier) xy dng Client Browser

WebServices

Giao din trang web, v cc lp x l tng ng cho cc giao din (code behind)

Cc lp x l trung gian gia data tier v presentation tier, cc lp ADO.NET

Database

Presentation Tier

Business Tier

Data Tier

Hnh 27.1Kin trc xy dng website Presentation Tier (mc giao din): cha cc thnh phn giao din ngi dng (UI) ca website, bao gm cc thnh phn qun l tng tc gia ngi dng v mc x l (bussiness). Bussiness Tier (mc x l): nhn yu cu t mc giao din v tr v kt qu ph thuc vo qu trnh x l. Hu ht cc kt qua x l s kin xy ra trn mc giao din u c thng qua mc x l ny, ngoi tr mt s nhng s kin validation). mc ny, cn gi n mc th 3 l mc d liu p tr li cc yu cu t mc giao din. Data Tier (mc d liu): ng vai tr lu tr d liu v gi chng n mc x l mi khi c yu cu. Sau y l hnh nh din t cho m hnh 3 lp ny:

Lu hnh ni b

Trang 437

thc hin m hnh 3 lp trn, website xy dng tng ng vi tng chc nng nh sau: STT Chc nng Presentation Tier (.aspx, .aspx.cs, .ascx, .ascx.cs) Register.aspx Register Login.aspx Login AccountManager.aspx AccountManager AccountManager.aspx AccountManager Search.aspx Search AmazonSearch.aspx AmazonSearch eBaySearch.aspx Business Tier (.cs, ADO.NET) LoginHelper LoginHelper LoginHelper Data Tier (Webservices, database) Database Database Database

1 2 3

ng k ti khon ng nhp Thay i thng tin ti khon Thay i mt khu Tm kim sn phm trn website Tm kim sn phm trn mt website

4 5

LoginHelper CatalogAccess

Database Database

AmazonAccess eBayAccess

WebServices

Lu hnh ni b

Trang 438

khc Xem thng tin sn phm

10

Tm sn phm tng t trn cc website khc vi sn phm ang xem Chuyn i gia mt s loi tin thng dng Thanh ton

BaySearch Catalog.aspx Catalog Product.aspx Product Product.aspx Product

CalalogAccess

Database

AmazonAccess eBayAccess

WebSercices

ProductList.ascx ProductList

CurrencyConverter

CurrencyWebse rvices

Checkout.aspx Checkout

paypalfunctions

PayPal Webservices (Express Checkout)

Chng ta s i vo chi tit 3 mc xy dng nn website: MC D LIU (Data Tier) mc ny, chng ta s t chc d liu cho website, bao gm 2 phn chnh: Cc bng d liu, v cc StoreProcedure a. Cc bng d liu. Website qun l sn phm theo 3 cp: Gian hng, Loi mt hng v sn phm. Trong , mi gian hng s c nhu mt hng khc nhau nh vy quan h gia 2 bng tblGianHang v tblLoaiMatHang l 1- . Gia sn phm v loi mt hng s c quan h l - v sn phm ny c th va l loi mt hng ny li va l loi mt hng kia. Do cn to thm mt bng tblSanPham_MatHang th hin mi quan h ny l hp l. Ngoi sn phm, chng ta cn phi qun l thng tin ngi dng tin trong vic mua hng, t hng trn website. Website s lu tr cc thng tin c bn ca ngi dng (ti khon, mt khu, email, a ch lin h, a ch nhn hng) Mt phn khng km phn quan trng cn c lu tr l n t hng. Mt n t hng c th c nhiu sn phm, v sn phm c t hng phi c cha trong danh mc sn phm m website hin c. Do mi quan h gia cc bng ny c m hnh quan h trn l hon ton ph hp. Ngoi ra, do website c s dng webservices, c th l tch hp cc webservices ca eBay, Amazon, Paypal nn mt phn d liu s dng tch hp. Ngha l chng ta s ly d liu t cc nh cung cp dch v web. trn a ra m hnh quan h, cng nh mt s ch thch v cch t chc d liu ca website. Sau y l m t chi tit cho tng bng d liu. tblLoaiMatHang MaMatHang: m ca mt hng, c kiu d liu l kiu int v khng cho php NULL, y l kha chnh ca bng. Lu hnh ni b Trang 439

TenMatHang: tn ca mt hng, c kiu d liu l kiu nvarchar(50) v khng cho php NULL. MaGianHang: y l m gian hng, c kiu d liu l kiu int v khng cho php NULL. MoTaMatHang: m t chi tit cho mt hng, c kiu d liu l kiu nvarchar(1000) v cho php NULL. tblGianHang MaGianHang: m ca gian hng, c kiu d liu l kiu int v khng cho php NULL, y l kha chnh ca bng. TenGianHang: tn ca gian hng, c kiu d liu l kiu nvarchar(50) v khng cho php NULL. MoTaGianHang: m t chi tit cho gian hng, c kiu d liu nvarchar(1000) v c th NULL. tblSanPham_MatHang MaSanPham: m ca sn phm, c kiu d liu l kiu int v khng cho php NULL. MaMatHang: m ca mt hng, c kiu d liu l kiu int v khng cho php NULL. Kha chnh ca bng l MaSanPham, MaMatHang. tblSanPham MaSanPham: m ca sn phm, c kiu d liu l kiu int v khng cho php NULL, y l kha chnh ca bng. TenSanPham: tn ca sn phm, c kiu d liu l kiu nvarchar(1000) v khng cho php NULL. MoTaSanPham: m t chi tit cho sn phm, c kiu d liu l kiu nvarchar(MAX) v khng cho php NULL. Gia: gi tin ca sn phm, c kiu d liu l kiu money v khng cho php NULL. Thumbnail: ng dn hnh nh nh ca sn phm, c kiu d liu l kiu nvarchar(50) v c th NULL. Image: ng dn hnh nh bnh thng ca sn phm, c kiu d liu l kiu nvarchar(50) v c th NULL. PromoFront: PromoDept: TacGia: tc gi ca sn phm, c kiu d liu l kiu nvarchar(1000) v khng cho php NULL. NXB: tn nh xut bn ca sn phm, c kiu d liu l kiu nvarchar(1000) v khng cho php NULL. NgonNgu: tn loi ngn ng, c kiu d liu l nvarchar(50) v khng cho php NULL. Solanmua: s ln mua ca sn phm, c kiu d liu l int v khng cho php NULL. NgayThem: ngy thm sn phm vo c s d liu, c kiu d liu l datetime v c th NULL. TenTimKiem: tn sn phm dng tm kim, c kiu d liu l nvarchar(500) v c th NULL. tblChiTietDonDatHang

Lu hnh ni b

Trang 440

MaDonDatHang: m ca n t hng, c kiu d liu l uniqueidentifier v khng cho php NULL. y l kha chnh ca bng. MaSanPham: m ca sn phm, c kiu d liu l int v khng cho php NULL. y cng l kha chnh ca sn phm. TenSanPham: tn ca sn phm, c kiu d liu l nvarchar(50) v khng cho php NULL. SoLuong: s lng sn phm c mua, c kiu d liu l int v khng cho php NULL. DonGia: n gi ca mt sn phm, c kiu d liu l money v khng cho php NULL. TongCong: tng gi tin ca cc sn phm c mua, c kiu d liu l money v c th NULL. tblDonDatHang MaDonDatHang: m ca n t hng, c kiu d liu l uniqueidentifier v khng cho php NULL. y l kha chnh ca bng. NgayTao: ngy to n t hng, c kiu d liu l smalldatetime v khng cho php NULL. NgayGiao: ngy giao sn phm, c kiu d liu l smalldatetime v c th NULL. XacNhan: xc nhn n t hng, c kiu d liu l bit v khng cho php NULL. HoanTat: hon tt n t hng, c kiu d liu l bit v khng cho php NULL. Huy: hy n t hng, c kiu d liu l bit v khng cho php NULL. GhiChu: ghi ch cho n t hng, c kiu d liu l nvarchar(1000) v cho php NULL. TenKhachHang: tn ca khch hng t mua sn phm, c kiu d liu l nvarchar(256) v khng cho php NULL. EmailKhachHang: email ca khch hng, c kiu d liu l nvarchar(256) v khng cho php NULL. TenNguoiTT: tn ca ngi thanh ton, c kiu d liu l nvarchar(256) v khng cho php NULL. DiaChiTT1: a ch th nht ca ngi thanh ton, c kiu d liu l nvarchar(256) v khng cho php NULL. DiaChiTT2: a ch th hai ca ngi thanh ton, c kiu d liu l nvarchar(256) v cho php NULL. DienThoaiTT: in thoi ca ngi thanh ton, c kiu d liu l nvarchar(128) v khng cho php NULL. TenNguoiNH: tn ca ngi nhn hng, c kiu d liu l nvarchar(256) v khng cho php NULL. DiaChiNH1: a ch th nht ca ngi nhn, c kiu d liu l nvarchar(256) v khng cho php NULL. DiaChiNH2: a ch th hai ca ngi nhn, c kiu d liu l nvarchar(256) v cho php NULL. DienThoaiNH: in thoi ca ngi nhn, c kiu d liu l nvarchar(128) v khng cho php NULL. tblHoSoTaiKhoan MaTaiKhoan: m ti khon ca khch hng, c kiu d liu l uniqueidentifier v khng cho php NULL. y l kha chnh ca bng. CreditCard: th thanh ton ca khch hng, c kiu d liu l ntext v cho php NULL. Lu hnh ni b Trang 441

TenNguoiTT: tn ca ngi thanh ton, c kiu d liu l nvarchar(50) v khng cho php NULL. DiaChiTT1: a ch th nht ca ngi thanh ton, c kiu d liu l nvarchar(256) v khng cho php NULL. DiaChiTT2: a ch th hai ca ngi thanh ton, c kiu d liu l nvarchar(256) v cho php NULL. DienThoaiTT: in thoi ca ngi thanh ton, c kiu d liu l nvarchar(128) v khng cho php NULL. TenNguoiNH: tn ca ngi nhn hng, c kiu d liu l nvarchar(256) v khng cho php NULL. DiaChiNH1: a ch th nht ca ngi nhn, c kiu d liu l nvarchar(256) v khng cho php NULL. DiaChiNH2: a ch th hai ca ngi nhn, c kiu d liu l nvarchar(256) v cho php NULL. DienThoaiNH: in thoi ca ngi nhn, c kiu d liu l nvarchar(128) v khng cho php NULL. tblTaiKhoan MaTaiKhoan: m ti khon ca khch hng, c kiu d liu l uniqueidentifier v khng cho php NULL. y l kha chnh ca bng. TaiKhoan: tn ti khon ca khch hng, c kiu d liu l nvarchar(50) v khng cho php NULL. QuyenTaiKhoan: quyn ca khch hng, c kiu d liu l int v khng cho php NULL. MatKhau: mt khu ca ti khon, c kiu d liu l nvarchar(128) v khng cho php NULL. CauHoiBaoMat: cu hi bo mt ca ti khon, c kiu d liu l nvarchar(256) v c th NULL. CauTraLoi: cu tr li cho cu hi bo mt, c kiu d liu l nvarchar(128) v c th NULL. Email: email kch hot ti khon, c kiu d liu l nvarchar(256) v khng cho php NULL. DaKichHoat: ti khon kch hot, c kiu d liu l bit v khng cho php NULL. DaDangXuat: ti khon ng xut, c kiu d liu l bit v khng cho php NULL. NgayTao: ngy ti khon c to, c kiu d liu l datetime v khng cho php NULL. NgayDangNhapCuoi: ngy ti khon ng nhp ln cui, c kiu d liu l datetime v cho php NULL. NgayDoiMatKhauCuoi: ngy ti khon i mt khu, c kiu d liu l datetime v cho php NULL. SoLanSaiMatKhau: s ln sai mt khu khi ti khon ng nhp, c kiu d liu l int v khng cho php NULL. NgayKhoaTaiKhoanDoSaiMatKhau: ngy ti khon b kha do ng nhp sai mt khu vt qu s ln cho php, c kiu d liu l datetime v khng cho php NULL.

Lu hnh ni b

Trang 442

S quan nim

Lu hnh ni b

Trang 443

Lu hnh ni b

Trang 444

b. Store Procedure Store Procedure (th tc lu tr): l cc cu lnh SQL c thc thi trc tip trn my cha SQL Database. Store Procedure cng ging nh cc hm hoc cc th tc trong cc ngn ng lp trnh, c ngha l n c th nhn vo cc tham s v tr v kt qu cho chng trnh gi n. Vic dng Store Procedure gip cho vic thc thi cc cu lnh nhanh hn nhiu so vi vic thc thi t Server Code, ngha l n s khng phi bin dch li m chy trc tip m my c bin dch. ng thi lm gim ng k lu lng lu thng qua mng bi n s khng phi to li kt ni. Sau y l mt s Store Procedure quan trng s dng cho website: LayCacGianHang Tn Ly danh sch cc gian hng ca website Chc nng y l Store Procedure n gin h tr xy dng menu website M t Tham s (Khng c) Tn tham s Kiu ngha

Tn Chc nng M t

ThmGianHang Thm vo mt gian hng cho website V kha ca gian hng l kiu int t tng, nn ch cn thm vo 2 tham s cho gian hng Tham s Tn tham s Kiu ngha nvarchar(50) nvarchar(50) Tn ca gian hng M t v gian hng

@TenGianHang @MoTaGianHang Tn Chc nng M t

XoaGianHang Xa mt gian hng cho website Tham s Kiu Int

Tn tham s @MaGianHang Tn Chc nng M t

ngha Kha ca gian hng

ThemMatHang Thm mt loi mt hng vo trong mt gian hng Tham s Kiu Int nvarchar(50) Nvarchar(1000)

Tn tham s @MaGianHang @TenMatHang @MoTaMatHang

ngha Kha ca gian hng Tn ca loi mt hng M t v loi mt hng

Lu hnh ni b

Trang 445

Tn Chc nng M t

ThemSanPham Thm mt sn phm vo website Tham s Kiu Int nvarchar(1000) nvarchar(max) Money Nvarchar(50) Nvarchar(50) Bit Bit

Tn tham s @MaMatHang @TenSanPham @MoTaSanPham @Gia @Thumbnail @Image @PromoFront @PromoDept

ngha Kha ca gian hng Tn ca sn phm M t v sn phm Gi ca sn phm Lu ng dn ca file thumbnail sn phm Lu ng dn ca file hnh sn phm nh du sn phm c c hin th ngay trang ch hay khng nh du sn phm c c hin th ti trang u ca mi gian hng hay khng Tn tc gi Tn nh xut bn Ngn ng c vit trn sn phm Ngy thm sn phm vo website

@TacGia @NXB @NgonNgu @NgayThem Tn Chc nng M t

Nvarchar(1000) Nvarchar(1000) Nvarchar(50) Datetime

XoaSanPham Xa mt sn phm trong website Tham s Kiu Int

Tn tham s @MaSanPham

ngha Kha ca sn phm

Tn Chc nng M t

LayCacLoaiMatHangTrongGianHang Ly danh sch cc loi mt hng ph thuc vo gian hng c chn Danh sch tr v c dng xy dng sub menu Tham s (Khng c) Tn tham s Kiu ngha Int Da vo m gian hng ny ly danh sch cc loi mt hng tng ng c trong gian hng Trang 446

@MaGianHang

Lu hnh ni b

Tn Chc nng M t

LaySanPhamTheoLoaiMatHang Ly danh sch cc sn phm theo loi mt hng c chn Danh sch sn phm tr v s c hin th mi khi ngi dng chn mt loi mt hng no . Th tc ny cn c tc dng h tr phn trang bng cch tnh ton thng qua cc d liu u vo, v tr v danh sch cc sn phm ph hp. Tham s (Khng c) Tn tham s Kiu ngha Int Int Int Da vo m mt hng ny ly danh sch cc sn phm tng ng Qui nh di m t sn phm khi c hin th ln website Tham s ny h tr cho chc nng phn trang, trang cn iu hng ti s c truyn vo thng qua tham s ny Qui nh s sn phm c trn 1 trang Tng s lng sn phm c trong loi mt hng c ch nh

@MaMatHang @DoDaiMoTaSanPham @SoTrang

@SoSanPhamTrenTrang @SoLuongSanPham

Int Int (Output)

Tn Chc nng M t

LaySanPhamChoTrangChinhTheoGianHang Ly danh sch cc sn phm s c hin th ln trang chnh ca mi gian hng khi c chn Danh sch sn phm tr v s c hin th mi khi ngi dng chn mt loi gian hng (menu) no . Th tc ny cn c tc dng h tr phn trang bng cch tnh ton thng qua cc d liu u vo, v tr v danh sch cc sn phm ph hp. Tham s (Khng c) Tn tham s Kiu ngha Int Int Int Da vo m mt hng ny ly danh sch cc sn phm tng ng Qui nh di m t sn phm khi c hin th ln website Tham s ny h tr cho chc nng phn trang, trang cn iu hng ti s c truyn vo thng qua tham s ny Qui nh s sn phm c trn 1 trang Tng s lng sn phm c trong loi mt hng c ch nh Trang 447

@MaMatHang @DoDaiMoTaSanPham @SoTrang

@SoSanPhamTrenTrang @SoLuongSanPham Lu hnh ni b

Int Int (Output)

Tn Chc nng M t

LaySanPhamChoTrangChinh Ly danh sch cc sn phm s c hin th ln trang ch ca website Danh sch sn phm tr v s c hin th mi khi ngi dng vo trang ch ca website. Th tc ny cn c tc dng h tr phn trang bng cch tnh ton thng qua cc d liu u vo, v tr v danh sch cc sn phm ph hp. Tham s (Khng c) Tn tham s Kiu ngha Int Int Int Da vo m mt hng ny ly danh sch cc sn phm tng ng Qui nh di m t sn phm khi c hin th ln website Tham s ny h tr cho chc nng phn trang, trang cn iu hng ti s c truyn vo thng qua tham s ny Qui nh s sn phm c trn 1 trang Tng s lng sn phm c trong loi mt hng c ch nh

@MaMatHang @DoDaiMoTaSanPham @SoTrang

@SoSanPhamTrenTrang @SoLuongSanPham

Int Int (Output)

trn l mt s Store Procedure c dng vo vic ly danh sch cc gian hng, mt hng cng nh sn phm cho website ty vo tng trng hp iu hng. Ngoi ra cn mt s th tc khc c tc dng v tham s tng t : LaySanPhamMoiNhat, LaySanPhamBanChay Cc th tc lin quan n ti khon ngi dng TaoTaiKhoan Tn To mt ti khon ngi dng trn website Chc nng M t Tham s Tn tham s Kiu @MaTaiKhoan @TaiKhoan @MatKhau @Email @TenNguoiTT @DiaChiTT1 @DiaChiTT2 @DienThoaiTT @TenNguoiNH1 @DiaChiNH1 Lu hnh ni b Uniqueidentifier Nvarchar(50) Nvarchar(128) Nvarchar(256) Nvarchar(50) Nvarchar(256) Nvarchar(256) Nvarchar(128) Nvarchar(50) Nvarchar(256)

ngha Kha Ti khon ng nhp Mt khu a ch email ca khch hng Tn ngi thanh ton a ch thanh ton 1 ia ch thanh ton 2 S in thoi lin lc thanh ton Tn ngi nhn hng a ch nhn hng 1 Trang 448

@DiaChiNH2 @DienThoaiNH

Nvarchar(256) Nvarchar(128)

a ch nhn hng 2 S in thoi lin lc nhn hng

Tn Chc nng M t

LayThongTinTaiKhoan Ly tt c thng tin lin quan n ti khon c ch nh Tham s Kiu Nvarchar(50)

Tn tham s @TaiKhoan

ngha Ti khon ca ngi dng

Cc Store Procedure lin quan n n hng: Website ch cho php ngi dng c ti khon mi c thanh ton gi hng. Trng hp ngi dng cha c ti khon mun thanh ton th s to ti khon theo tng bc thanh ton. ThemDonDatHang Tn Thm mt n hng khi khch hng bt u qui trnh thanh ton Chc nng M t Tham s Tn tham s Kiu ngha @MaDonDatHang @TaiKhoan @NgayGiao @LoaiVanChuyen @LoaiTien @TyGia Tn Chc nng M t Uniqueidentifier Nvarchar(50) Smalldatetime Int Nvarchar(50) Float Kha ca n t hng Ti khon ngi t hng Ngy giao hng (trong ngy, 3 ngy, 1 tun ) Loi tien s dng lc thanh ton T gi lc thanh ton

ThemSanPhamVaoChiTietDonDatHang Thm 1 sn phm vo chi tit n t hng Mt n t hng c th c nhiu sn phm, do th tc ny s ng vai tr them vo tng sn phm tng ng vi n hng ang c x l Tham s Tn tham s Kiu ngha Uniqueidentifier Int Nvarchar(50) Int Money Kha ca n t hng M sn phm c thm vo n t hng Tn sn phm S lng sn phm c mua n gi sn phm Trang 449

@MaDonDatHang @MaSanPham @TenSanPham @SoLuong @DonGia Lu hnh ni b

Tn Chc nng M t

LayThongTinDonDatHang Ly cc thng tin cn thit ca 1 n t hng bao gm tng tin ca n hng Tham s Kiu Uniqueidentifier

Tn tham s @MaDonDatHang Tn Chc nng M t Tn tham s @MaDonDatHang Tn Chc nng M t

ngha Kha ca n t hng

LaySanPhamTrongDonDatHang Ly danh sch cc sn phm trong n t hng (m sn phm, tn sn phm, s lng, n gi) Tham s Kiu Uniqueidentifier

ngha Kha ca n t hng

XoaDonDatHang Xa n t hng Tham s Kiu Uniqueidentifier

Tn tham s @MaDonDatHang Tn Chc nng M t

ngha Kha ca n t hng

XacNhanDonDatHang nh du xc nhn n hng c duyt Tham s Kiu Uniqueidentifier

Tn tham s @MaDonDatHang Tn Chc nng M t

ngha Kha ca n t hng

HoanTatDonDatHang Xc nhn n hng hon tt Tham s Kiu Uniqueidentifier

Tn tham s @MaDonDatHang Tn Chc nng Lu hnh ni b

ngha Kha ca n t hng

HuyDonDatHang Hy n hng Trang 450

M t Tn tham s @MaDonDatHang Tn Chc nng M t Tham s Kiu Uniqueidentifier ngha Kha ca n t hng

LayCacDonHangTrongKhoangThoiGian Ly danh sch cc n hng trng 1 khon thi gian ch nh Tham s Kiu

Tn tham s

ngha

@NgayBatDau Smalldatetime Thi gian bt u @NgayKetThuc Smalldatetime Thi gian kt thc Ngoi cc th tc lu tr c lit k trn website cn s dng mt s store procedure khc, xin tham kho chi tit trong phn c s d liu ca website

Lu hnh ni b

Trang 451

Chng 16:

THIT K WEBSITE BN HNG MC X L (Bussiness Tier)

mc d liu, chng ta xy dng c c s d liu v cc store procedure cho website bn sch qua mng. Trong mc x l ny, chng ta s xy dng cc lp C#, thc hin vic ly d liu, x l d liu t database sau tr kt qu v cho mc trn (Presentation Tier) mi khi c yu cu. Cc lp C# chnh c s dng: Tn lp File (.cs) Chc nng GenericDataAccess GenericDataAccess.cs C tc dng thc thi cc chc nng c bn s c s dng li nhiu ln mi khi cn truy xut n database. OnlineStoreConfiguration OnlineStoreConfiguration.cs Lp ny gip ly c nhng thng s cu hnh ca website c lu trong file web.config Utilities Utilities.cs Cha cc hm x l thng thng nh gi email, log li v nhu chc nng khc s c s dng nhiu trong website CatalogAccess CatalogAccess.cs y l lp quan trng, cha tt c cc phng thc tng tc vi sn phm, nh ly danh sch cc sn phm, cp nht thng tin 1 sn phm v.v LinkBuilder LinkBuilder.cs C tc dng to ra cc ng link, h tr trong vic iu hng cc trang trong website LoginHelper LoginHelper.cs Lp ny c xy dng qun l ngi dng, truy Lu hnh ni b Trang 452

ShoppingCartAccess

ShoppingCartAccess.cs

OrdersAccess

OrdersAccess.cs

AmazonAccess

AmazonAccess.cs

eBayAccess

eBayAccess.cs

xut, chnh sa thng tin ngi dng. Qun l vn ng nhp v ng xut ca user Cha cc chc nng lin quan n gi hng, cp nht, thm xa sa gi hng Cha cc phng thc thao tc vi n t hng trong database (thm, cp nht, xa ) Lp ny cung cp cc phng thc thao tc vi webservices ca Amazon Lp ny cung cp cc phng thc thao tc vi webservices ca eBay

Cc lp trn c ci t theo ngn ng C# chi tit chc nng, ci t nh sau: 1. OnlineStoreConfigurations: Lp tnh (static class) dng ly cu hnh website t file web.config. using System.Configuration; using System; public static class OnlineStoreConfigurations { private static string dbConnectionString; private static string dbProviderName; private readonly static int productsPerPage; private readonly static int productDescriptionLength; private readonly static string siteName; static OnlineStoreConfigurations() { dbConnectionString = ConfigurationManager.ConnectionStrings["OnlineStoreConnection"].ConnectionString; Lu hnh ni b Trang 453

dbProviderName = ConfigurationManager.ConnectionStrings["OnlineStoreConnection"].ProviderName; productsPerPage = System.Int32.Parse(ConfigurationManager.AppSettings["ProductsPerPage"]); productDescriptionLength = System.Int32.Parse(ConfigurationManager.AppSettings["ProductDescriptionLength"]); siteName = ConfigurationManager.AppSettings["SiteName"]; } public static string DbConnectionString { get { return dbConnectionString; } } public static string DbProviderName { get { return dbProviderName; } } public static string MailServer { get { return ConfigurationManager.AppSettings["MailServer"]; } } public static string MailUsername { get { return ConfigurationManager.AppSettings["MailUsername"]; } } public static string MailPassword Lu hnh ni b Trang 454

{ get { return ConfigurationManager.AppSettings["MailPassword"]; } } public static string MailFrom { get { return ConfigurationManager.AppSettings["MailFrom"]; } } public static bool EnableErrorLogEmail { get { return bool.Parse(ConfigurationManager.AppSettings["EnableErrorLogEmail"]); } } public static string ErrorLogEmail { get { return ConfigurationManager.AppSettings["ErrorLogEmail"]; } } public static int ProductsPerPage { get { return productsPerPage; } } public static int ProductDescriptionLength { Lu hnh ni b Trang 455

get { return productDescriptionLength; } } public static string SiteName { get { return siteName; } } public static int CartPersistDays { get { return Int32.Parse(ConfigurationManager.AppSettings["CartPersistDays"]); } } public static string PaypalUrl { get { return ConfigurationManager.AppSettings["PaypalUrl"]; } } public static string PaypalEmail { get { return ConfigurationManager.AppSettings["PaypalEmail"]; } } public static string PaypalCurrency { get { Lu hnh ni b Trang 456

return ConfigurationManager.AppSettings["PaypalCurrency"]; } } public static string PaypalReturnUrl { get { return ConfigurationManager.AppSettings["PaypalReturnUrl"]; } } public static string PaypalCancelUrl { get { return ConfigurationManager.AppSettings["PaypalCancelUrl"]; } } } y l mt lp n gin, bao gm cc Properties phc v cho vic ly cc thng s cu hnh cho website bn sch 2. GenericAccess: C tc dng thc thi cc chc nng c bn s c s dng li nhiu ln mi khi cn truy xut n database using System; using System.Data; using System.Data.Common; /// <summary> /// Summary description for GenericDataAccess /// </summary> public static class GenericDataAccess { static GenericDataAccess() { // // TODO: Add constructor logic here // } public static DataTable ExecuteSelectCommand(DbCommand command) Lu hnh ni b Trang 457

{ DataTable table; try { command.Connection.Open(); DbDataReader reader = command.ExecuteReader(); table = new DataTable(); table.Load(reader); reader.Close(); } catch (Exception ex) { Utilities.LogError(ex); throw; } finally { command.Connection.Close(); } return table; } public static DbCommand CreateCommand() { string dataProviderName = OnlineStoreConfigurations.DbProviderName; string connectionString = OnlineStoreConfigurations.DbConnectionString; DbProviderFactory factory = DbProviderFactories.GetFactory(dataProviderName); DbConnection conn = factory.CreateConnection(); conn.ConnectionString = connectionString; DbCommand comm = conn.CreateCommand(); comm.CommandType = CommandType.StoredProcedure; return comm; } public static int ExecuteNonQuery(DbCommand command) { int affectedRows = -1; try { command.Connection.Open(); Lu hnh ni b Trang 458

affectedRows = command.ExecuteNonQuery(); } catch (Exception e) { Utilities.LogError(e); throw; } finally { command.Connection.Close(); } return affectedRows; } public static string ExecuteScalar(DbCommand command) { string value = ""; try { command.Connection.Open(); value = command.ExecuteScalar().ToString(); } catch (Exception ex) { Utilities.LogError(ex); throw; } finally { command.Connection.Close(); } return value; } } Chc nng chnh ca lp ny l to nn nhng i tng ADO.NET (DbConnection, DbCommand s dng trong namespace System.Data.Common ) nhm mc ch trnh s dng cc lp truy xut d liu c th no nh SqlConnection, SqlComand hoc , thay vo ng dng ca chng ta s quyt nh provider no c s dng ngay ti lc chy (runtime) da vo chui kt ni c cung cp (connection string) Phng thc quan trng quyt nh u im ni trn l CreateCommand() public static DbCommand CreateCommand() Lu hnh ni b Trang 459

{ string dataProviderName = OnlineStoreConfigurations.DbProviderName; string connectionString = OnlineStoreConfigurations.DbConnectionString; DbProviderFactory factory = DbProviderFactories.GetFactory(dataProviderName); DbConnection conn = factory.CreateConnection(); conn.ConnectionString = connectionString; DbCommand comm = conn.CreateCommand(); comm.CommandType = CommandType.StoredProcedure; return comm; } u tin chng ta s to mt i tng DbProviderFactory ly provider c th. Sau to mt i tng DbConnection (tng ng vi SqlConnection nu provider l System.Data.SqlClient) thng qua factory method ca i tng DbProvider va c to ra. Cui cng l to ra i tng DbCommand (tng t nh SqlCommand) Cc phng thc cn li ca lp ny: ExecuteSelectCommand, ExecuteNonQuery, ExecuteScalar s nhn mt tham s truyn vo l mt i tng DbCommand v thc thi chc nng tng ng. Vic s dng lp ny nh th no s c cp n trong cc phn sau: 3. CatalogAccess: Nh trnh by trn chng ta to mt lp GenericAccess c tc dng to ra cc i tng DbCommand v thc thi cc chc nng ty thuc vo i s u vo. lp CatalogAccess ny s m t cch s dng cc chc nng c ci t trong lp GenericAccess thng qua mt vi phng thc sau y. bit c cch ci t cc phng thc khc, xin tham kho source code. public static DataTable GetProductsInCategory(string categoryId, string pageNumber, out int howManyPages) { DbCommand comm = GenericDataAccess.CreateCommand(); comm.CommandText = "LaySanPhamTheoLoaiMatHang"; DbParameter param = comm.CreateParameter(); param.ParameterName = "@MaMatHang"; param.Value = categoryId; param.DbType = DbType.Int32; comm.Parameters.Add(param); param = comm.CreateParameter(); param.ParameterName = "@DoDaiMoTaSanPham"; param.Value = OnlineStoreConfigurations.ProductDescriptionLength; param.DbType = DbType.Int32; Lu hnh ni b Trang 460

comm.Parameters.Add(param); param = comm.CreateParameter(); param.ParameterName = "@SoTrang"; param.Value = pageNumber; param.DbType = DbType.Int32; comm.Parameters.Add(param); param = comm.CreateParameter(); param.ParameterName = "@SoSanPhamTrenTrang"; param.Value = OnlineStoreConfigurations.ProductsPerPage; param.DbType = DbType.Int32; comm.Parameters.Add(param); param = comm.CreateParameter(); param.ParameterName = "@SoLuongSanPham"; param.Direction = ParameterDirection.Output; param.DbType = DbType.Int32; comm.Parameters.Add(param); DataTable table = GenericDataAccess.ExecuteSelectCommand(comm); int howManyProducts = Int32.Parse(comm.Parameters["@SoLuongSanPham"].Value.ToString()); howManyPages = (int)Math.Ceiling((double)howManyProducts / (double)OnlineStoreConfigurations.ProductsPerPage); return table; } Phng thc ny m nhn cng vic ly v danh sch sn phm nm trong mt loi mt hng c th c truyn vo thng qua tham s categoryId, s trang c ly pageNumber, v 1 tham s output cho bit tng s trang sn phm c trong loi mt hng. Chng ta s to mt i tng DbCommand thng qua phng thc CreateCommand() ca lp GenericAccess va c to trn. Tip theo cn to cc tham s DbParameter tng ng vi Store Procedure tng ng. Trong phng thc ny s gi thc thi th tc: LaySanPhamTheoLoaiMatHang c xy dng trong phn data tier. Mi tham s s truyn vo tn tham s, kiu gi tr, kiu tham s input (mc nh) hoc output. Danh sch cc phng thc c bn c trong lp CatalogAccess: GetDePartments() Tn DataTable Kiu tr v Ly v danh sch cc gian hng Chc nng LayCacGianHang Store Procedure s Lu hnh ni b Trang 461

dng Tn tham s Tn Kiu tr v Chc nng Store Procedure s dng Tham s (khng c) Kiu GetDepartmentDetails() DepartmentDetails Ly chi tit mt gian hng c th da vo m gian hng LayChiTietGianHang ngha

Tn tham s departmentId Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu string GetCategoryDetails()

ngha M gian hng

CategoryDetails Ly chi tit mt loi mt hng c th da vo m loi mt hng LayChiTietGianHang

Tn tham s categoryId Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu string GetProductDetails()

ngha M loi mt hng

ProductDetails Ly chi tit mt sn phm c th da vo m sn phm LayChiTietSanPham

Tn tham s productId Tn Kiu tr v Chc nng Store Procedure s dng Lu hnh ni b

Tham s Kiu string GetCategoriesInDepartment()

ngha M gian hng

DataTable Ly danh sch loi mt hng trong mt gian hng c th LayCacLoaiMatHangTrongGianHang

Trang 462

Tn tham s departmentId Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu string

ngha M gian hng

GetCategoriesOnFrontPromo() DataTable Ly danh sch sn phm hin th trn trang ch LaySanPhamChoTrangChinh

Tn tham s pageNumber howManyPages (out) Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu string Int

ngha S trang cn iu hng n S trang c tr v

GetProductsInCategory () DataTable Ly danh sch sn phm thuc vo m loi mt hng no LaySanPhamTheoLoaiMatHang

Tn tham s categoryId pageNumber howManyPages (out)

Tham s Kiu string string Int

ngha M loi mt hng S trang cn iu hng ti Tng s trang c c

Cc phng thc s dng cho vic qun l sn phm website. UpdateDepartment() Tn Bool Kiu tr v Cp nht thng tin ca mt gian hng Chc nng CapNhatGianHang Store Procedure s dng Tham s Tn tham s Kiu id name description Lu hnh ni b string string string

ngha M gian hng Tn gian hng M t v gian hng Trang 463

Tn Kiu tr v Chc nng Store Procedure s dng

DeleteDepartment() Bool Xa mt gian hng XoaGianHang

Tn tham s id Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu string AddDepartment()

ngha M gian hng

Bool Thm mt gian hng mi ThemGianHang

Tn tham s name description Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu string string CreateCategory()

ngha Tn gian hng M t v gian hng

Bool Thm mt loi mt hng mi ThemMatHang

Tn tham s departmentId name description Tn Kiu tr v Chc nng Store Procedure s dng Lu hnh ni b

Tham s Kiu string string string UpdateCategory()

ngha M gian hng Tn loi mt hng M t v loi mt hng

Bool Cp nht thng tin mt loi mt hng CapNhatMatHang

Trang 464

Tn tham s Id name description Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu string string string DeleteCategory()

ngha M loi mt hng Tn loi mt hng M t v loi mt hng

Bool Xa mt loi mt hng XoaMatHang

Tn tham s id Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu string CreateProduct()

ngha M loi mt hng

Bool To mt sn phm mi ThemSanPham

Tn tham s maMatHang tenSanPham tacgia nxb moTaSanPham gia thumbnail image promoFront

Tham s Kiu string string string string string string string string string

ngha M loi mt hang Tn sn phm Tc gi Nh xut bn M t v sn phm Gi ca sn phm ng dn cha file thumbnail ng dn cha file hnh nh sn phm (True, hoc False) ch nh sn phm c c hin th trn trang ch hay khng (True, hoc False) ch nh sn phm c c hin th trn u mi gian hng Trang 465

promoDept

string

Lu hnh ni b

hay khng. ngaythem Tn Kiu tr v Chc nng Store Procedure s dng string UpdateProduct() Bool Cp nht thong tin mt sn phm CapNhatSanPham Ngy thm sn phm

Tn tham s maSanPham tenSanPham tacgia nxb moTaSanPham gia thumbnail image promoFront

Tham s Kiu string string string string string string string string string

ngha M sn phm Tn sn phm Tc gi Nh xut bn M t v sn phm Gi ca sn phm ng dn cha file thumbnail ng dn cha file hnh nh sn phm (True, hoc False) ch nh sn phm c c hin th trn trang ch hay khng (True, hoc False) ch nh sn phm c c hin th trn u mi gian hng hay khng. Ngy thm sn phm

promoDept

string

ngaythem Tn Kiu tr v Chc nng Store Procedure s dng

string DeleteProduct()

Bool Xa mt sn phm XoaSanPham

Tn tham s maSanPham

Tham s Kiu string

ngha M sn phm cn xa

Lu hnh ni b

Trang 466

Tn Kiu tr v Chc nng Store Procedure s dng

AssignProductToCategory() Bool Gn mt sn phm vo mt loi mt hng ChiDinhLoaiMatHangChoSanPham

Tn tham s maSanPham maMatHang Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu string string MoveProductToCategory()

ngha M sn phm M loi mt hng

Bool i loi mt hang cho sn phm DoiLoaiMatHangChoSanPham

Tn tham s maSanPham maMatHangCu maMatHangMoi Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu string string string

ngha M sn phm M loi mt hang c M loi mt hang mi

RemoveProductFromCategory() Bool Xa sn phm khi loi mt hang XoaSanPhamTrongLoaiMatHang

Tn tham s maSanPham maMatHang

Tham s Kiu string string

ngha M sn phm M loi mt hng

4. LoginHelper: Tc dng ca lp ny dng x l cc s kin xy ra lin quan n user nh ng nhp, to ti khon, chnh sa thng tin ti khon Sau y xin c cp n mt s phng thc c bn c xy dng trong lp ny: Login Tn Bool Kiu tr v Lu hnh ni b Trang 467

Chc nng Store Procedure s dng

c s dng mi khi user ng nhp vo h thng t giao din web. Tr v True nu ng nhp thnh cng v False nu tht bi

Tn tham s acc pass authorityNo

Tham s Kiu string string string (out)

ngha Ti khon Mt khu Quyn ngi dung (user hay admin)

Tn Kiu tr v Chc nng Store Procedure s dng

CheckAvailbleAccount Bool Kim tra ti khon c th c s dng hay khng trong qu trnh ng k mt ti khon mi.

Tn tham s acc Tn Kiu tr v Chc nng Store Procedure s dng Tn tham s email Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu string CheckAvailbleEmail

ngha Ti khon

Bool Kim tra email c th c s dng hay khng trong qu trnh ng k mt ti khon mi.

Tham s Kiu string CreateAccount

ngha a ch email

Bool To ti khon mi, tr v True nu thnh cng v False nu tht bi TaoTaiKhoan

Tham s Lu hnh ni b Trang 468

Tn tham s acc pass Email Billingname Billingaddress1 Billingaddress2 Billingphone Shippingname Shippingaddress1 Shippingaddress2 Shippingphone Tn Kiu tr v Chc nng Store Procedure s dng

Kiu string String String String String String String String String String String GetAccountDetails

ngha Ti khon Mt khu a ch email Tn ngi thanh ton a ch thanh ton 1 a ch thanh ton 2 S in thoi thanh ton Tn ngi nhn hang a ch ngi nhn hang 1 a ch ngi nhn hang 2 in thoi nhn hang

AccountDetails Ly tt c thng tin lin quan n user LayThongTinTaiKhoan

Tn tham s acc

Tham s Kiu string

ngha Ti khon

5. ShoppingCartAccess: Lp ny thc hin cc chc nng nh to gi hng, thm xa sa v cp nhp gi hng. Bi v gi hng c xy dng bng Session nn hu ht cc phng thc trong lp ny s khng thc cc Store procedure ma ch lu trn i tng Session BookStoreCart GetShoppingCart Tn DataTable Kiu tr v Ly danh sch cc sn phm trong gi hang, nu gi hang cha c th s Chc nng to gi hang mi. Store Procedure s dng Tham s (khng c) Tn tham s Kiu ngha Tn Kiu tr v Lu hnh ni b AddToShoppingCart Bool Trang 469

Chc nng Store Procedure s dng

Thm mt sn phm vo trong gi hang

Tn tham s MaSanPham Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu String UpdateItemInShoppingCart

ngha M sn phm

Bool Cp nht s lng cho sn phm tng ng c trong gi hng

Tn tham s productID quanlity Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu String String DeleteItemInShoppingCart

ngha M sn phm S lng

Bool Xa mt sn phm ra khi gi hang

Tn tham s productID Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu String CreateOrder

ngha M sn phm

Bool To mt n hang vi gi hang tng ng ThemDonDatHang

Tn tham s Ordered Account Lu hnh ni b

Tham s Kiu String String

ngha M n hng Ti khon ngi mua Trang 470

shippingType Currency Rate Tn Kiu tr v Chc nng Store Procedure s dng

String String Double AddProductInOrder

Loi vn chuyn Loi tin t T gi hin ti

Int Cp nht s lng cho sn phm tng ng c trong gi hng ThemSanPhamVaoChiTietDonDatHang

Tn tham s ordered productId productName quanlity unitPrice

Tham s Kiu String String String String String

ngha M n t hng M sn phm Tn sn phm S lng n gi

6. OrdersAccess: Lp ny s thc hin cc chc nng qun l cc n t hng, ly thng tin ca mt n t hng, nh u n hng hon tt, c duyt, hoc xa n hng GetInfo Tn OrderInfo Kiu tr v Ly thng tin c bn ca 1 n hang Chc nng LayThongTinDonDatHang Store Procedure s dng Tham s Tn tham s Kiu ngha Ordered Tn Kiu tr v Chc nng Store Procedure s dng String GetDetails LaySanPhamTrongDonDatHang Ly thng tin cc sn phm trong n t hng LaySanPhamTrongDonDatHang M n t hng

Tn tham s Lu hnh ni b

Tham s Kiu

ngha Trang 471

Ordered Tn Kiu tr v Chc nng Store Procedure s dng

String Update

M n t hng

Void Cp nht thng tin cho mt n t hang CapNhatDonDatHang

Tn tham s orderInfo

Tham s Kiu OrderInfo

ngha Mt i tng cha cc thng tin n t hng

Tn Kiu tr v Chc nng Store Procedure s dng

MarkVerified Void nh du n hang c xc nhn XacNhanDonDatHang

Tn tham s ordered Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu String MarkCompleted

ngha M n t hang

Void nh du n hang hon tt HoanTatDonDatHang

Tn tham s ordered Tn Kiu tr v Chc nng Store Procedure s dng

Tham s Kiu String MarkCanceled

ngha M n t hang

Void nh du n hang b hy HuyDonDatHang

Tham s Lu hnh ni b Trang 472

Tn tham s ordered

Kiu String

ngha M n t hang

7. AmazonAcess,eBayAccess: Chc nng chnh ca 2 lp ny l thc hin giao tip vi web services c Amazon, eBay cung cp. Trong mi lp s c mt s bin v cch thit lp tham s ring, nhng u c phng thc ly cc sn phm t cc web serivces ny. GetAmazonProducts Tn DataTable Kiu tr v Ly v danh sch sn phm t Amazon thng qua web services Chc nng Store Procedure s dng Tham s Tn tham s Kiu ngha Keywords String T kha tm v cc sn phm tng ng trn Amazon S trang m chng ta mun ly v Ly ra s trang tm c trn Amazon vi t kha c cung cp

Page howmanypage

String Int (out)

Tn Kiu tr v Chc nng Store Procedure s dng

GeteBayProducts DataTable Ly v danh sch sn phm t eBay thng qua web services

Tn tham s Keywords

Tham s Kiu String

ngha T kha tm v cc sn phm tng ng trn Amazon S trang m chng ta mun ly v Ly ra s trang tm c trn Amazon vi t kha c cung cp

Page howmanypage

String Int (out)

Lu hnh ni b

Trang 473

n y chng ta gn nh hon thnh vic xy dng mc th 2 trong m hnh 3 lp xy dng web site bn sch qua mng. Phn tip theo chng ta s xy dng cc thnh phn thuc lp th 3 Presentation Tier bao gm cc Master Page, User Control, Web Page

Lu hnh ni b

Trang 474

Chng 17:

THIT K WEBSITE BN HNG MC TRNH DIN (Presentation Tier)

mc ny, chng ta s xy dng cc Master Page, User Control v Web Page. Di y l mt s thnh phn c bn ca website. Master Page BookStore.master Qui nh layout chnh cho cc trang m ngi dng xem Admin.master Qui nh layout cho cc trang cho ngi dng c quyn admin vo qun l website User Control AmazonProductList.ascx AmazonSearch.ascx CartSumary.ascx CartSumary2.ascx CategoriesList.ascx DepartmentsList.ascx eBayProductList.ascx eBaySearch.ascx Menu.ascx Pager.ascx ProductList.ascx SearchBook.ascx UserInfo.ascx Web page AccountManager.aspx AdminDepartment.aspx AdminOrderDetails.aspx AdminOrder.aspx AdminProductDetails.aspx AdminProducts.aspx Catalog.aspx Checkout.aspx CheckoutInfo.aspx ConfirmCheckoutInfo.aspx Default.aspx Login.aspx ShoppingCart.aspx

Lu hnh ni b

Trang 475

Trong phn ny chng ta khng i vo xy dng chi tit tng webpage m ch trnh by b cc cc Master Page v mt s User Control Master Page: Logo, banner

SearchBook.ascx UserInfo.ascx

Menu.ascx

ContentPlaceHolder

CartSumary.ascx

AmazonSearch.ascx

eBaySearch.ascx

Info

Lu hnh ni b

Trang 476

Admin.master UserInfo.ascx

Logo, banner ContentPlaceHolder

Pager.ascx 1. Thm mt Web User Control mi c tn l Pager vo th mc UserControls (chn with a code behind file). 2. phn Source View, thit k nh on m sau: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="Pager.ascx.cs" Inherits="UserControl_Pager" %> <p> Trang&nbsp; #<asp:Label ID="currentPageLabel" runat="server" /> &nbsp;trong s <asp:Label ID="howManyPagesLabel" runat="server" /> &nbsp;trang | <asp:HyperLink ID="previousLink" Runat="server">Trc</asp:HyperLink> <asp:Repeater ID="pagesRepeater" runat="server"> <ItemTemplate> <asp:HyperLink ID="hyperlink" runat="server" Text='<%# Eval("Page") %>' NavigateUrl='<%# Eval("Url") %>'/> </ItemTemplate> </asp:Repeater> <asp:HyperLink ID="nextLink" Runat="server">Tip</asp:HyperLink> </p> 3. Chuyn qua Design View, control ca chng ta s nh sau:

4. file code behind iu chnh phn code nh sau: using System; public struct PageUrl { private string page; Lu hnh ni b Trang 477

private string url; // Page and Url property definitions public string Page { get { return page; } } public string Url { get { return url; } } // constructor public PageUrl(string page, string url) { this.page = page; this.url = url; } } public partial class UserControl_Pager : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } private const int half = 5; public void Show(int currentPage, int howManyPages, string firstPageUrl, string pageUrlFormat, bool showPages) { if (howManyPages > 1) { this.Visible = true; currentPageLabel.Text = currentPage.ToString(); Lu hnh ni b Trang 478

howManyPagesLabel.Text = howManyPages.ToString();

if (currentPage == 1) { previousLink.Enabled = false; } else { previousLink.NavigateUrl = (currentPage == 2) ? firstPageUrl : String.Format(pageUrlFormat, currentPage - 1); } if (currentPage == howManyPages) { nextLink.Enabled = false; } else { nextLink.NavigateUrl = String.Format(pageUrlFormat, currentPage + 1); } if (showPages) { PageUrl[] pages = new PageUrl[half*2]; if (currentPage > half) { int i = currentPage - half; pages[0] = new PageUrl(i.ToString(), string.Format(pageUrlFormat, i)); int count = 1; i++; while ((i < currentPage + half ) && (i <= howManyPages)) { pages[count] = new PageUrl(i.ToString(), string.Format(pageUrlFormat, i)); count++; i++; } pages[5] = new PageUrl((currentPage).ToString(), ""); } else Lu hnh ni b Trang 479

{ pages[0] = new PageUrl("1",firstPageUrl); int i = 2; while ((i <= half + currentPage - 1) && (i <= howManyPages)) { pages[i-1] = new PageUrl(i.ToString(), string.Format(pageUrlFormat, i)); i++; } pages[currentPage - 1] = new PageUrl((currentPage).ToString(), ""); } pagesRepeater.DataSource = pages; pagesRepeater.DataBind(); } } } } ProductsList.ascx 1. Thm mt Web User Control vo th mc UserControls, t tn l ProductsList 2. M Design View v ko th mt Pager t Solution Explore va c xy dng trn vo ProductsList control. 3. Tip tc ko vo mt i tng DataList vo ProductsList. 4. Tip tc ko vo mt Pager khc vo cui ca ProductsList. 5. phn Source s c chnh sa li nh sau: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="ProductsList.ascx.cs" Inherits="UserControl_ProductsList" %> <%@ Register src="Pager.ascx" tagname="Pager" tagprefix="uc1" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<uc1:Pager ID="topPager" runat="server" Visible="False" /> <script src="jsModalProgress.js" type="text/javascript"></script> <script type="text/javascript" language="javascript"> var ModalProgress = '<%= ModalProgress.ClientID %>'; </script> <table style="width:100%"> <tr> <td style="text-align:right"> <span style="font-style:oblique;font-size:14px">Chn loi tin: </span> <asp:DropDownList ID="ddlCurrency" runat="server" DataSourceID="SqlDataSource1" AutoPostBack="true" DataTextField="QuocGia" DataValueField="DonVi" Lu hnh ni b Trang 480

onselectedindexchanged="ddlCurrency_SelectedIndexChanged" Font-Size="14px"> </asp:DropDownList> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:OnlineStoreConnection %>" SelectCommand="SELECT DonVi, QuocGia, ThongDung FROM tblTienTe ORDER BY ThongDung DESC, DonVi"> </asp:SqlDataSource> <asp:HiddenField ID="hdRate" runat="server" /> </td> </tr> <tr> <td> <asp:Label ID="lblError" runat="server" ForeColor="Red"></asp:Label> </td> </tr> </table> <asp:Panel ID="panelUpdateProgress" runat="server"> <asp:UpdateProgress ID="UpdateProg1" DisplayAfter="0" runat="server" > <ProgressTemplate> <div style="position: relative; top: 2%; text-align: center; left: 4px; height: 70px; width: 150px;"> <img src="images/loading.gif" width="60px" height="60px" /> <br /> <span style="color:White">Vui lng ch....</span> </div> </ProgressTemplate> </asp:UpdateProgress> </asp:Panel> <cc1:ModalPopupExtender ID="ModalProgress" runat="server" TargetControlID="panelUpdateProgress" BackgroundCssClass="modalBackground" PopupControlID="panelUpdateProgress" /> <asp:DataList ID="list" runat="server" RepeatColumns="3" DataKeyField="MaSanPham" onitemcommand="list_ItemCommand" onitemdatabound="list_ItemDataBound"> <ItemTemplate> <table style="width:100%;"> <tr> <td style="width:100%; padding-left:10px"> <span style="font-size:12px; font-weight:bold; margin-left:20px"> <br style="line-height:10px" /> <asp:HyperLink ID="hplnkName" Height="30px" runat="server" NavigateUrl='<%# LinkBuilder.ToProduct(Eval("MaSanPham").ToString())%>' Text='<%# HttpUtility.HtmlEncode(Eval("TenSanPham").ToString()) %>'></asp:HyperLink> </span> </td> </tr> <tr> Lu hnh ni b Trang 481

<td style="padding-left:10px;border-left-color:Green; border-left-style:solid; border-left-width:1px"> <table> <tr> <td style="width:5px;"> </td> <td> <br style="line-height:10px"> <a href="<%# LinkBuilder.ToProduct(Eval("MaSanPham").ToString()) %>"> <img width="100px" height="110px" src="<%# LinkBuilder.ToProductImage(Eval("Thumbnail").ToString()) %>" border="0" alt="<%# HttpUtility.HtmlEncode(Eval("TenSanPham").ToString())%>"></a><br><br style="lineheight:9px"> </a> </td> <td> <br><br style="line-height:9px"><%# HttpUtility.HtmlEncode(Eval("MoTaSanPham").ToString()) %> </td> </tr> <tr> <td> </td> <td> </td> <td> <asp:LinkButton ID="btnAddToCart" runat="server" Text="Thm vo gi" Width="100px"></asp:LinkButton> </td> </tr> </table> </td> </tr> <tr> <td style="padding-left:10px;border-left-color:Green; border-left-style:solid; border-left-width:1px"> <table> <tr> <td> <asp:HiddenField ID="hd" runat="server" Value='<%#Eval("Gia") %>' /> <span class="productSpecialPrice"><asp:Label ID="lblPrice" runat = "server" Text='<%#FormatCurrency(Double.Parse(Eval("Gia").ToString()))%>'></asp:Label> </span> Lu hnh ni b Trang 482

<br style="line-height:3px"> <br style="line-height:6px"> </td> <td> <br /> <br style="line-height:6px"> </td> </tr> <tr> <td> </td> </tr> </table> </td> </tr> <tr style="width:80%"> <td colspan="6" style="background:url(images/1_bg1.gif); width:1px; height:1px"> <img alt="" src="images/spacer.gif" width="1" height="1"></td> </tr> </table> </ItemTemplate> </asp:DataList> <script language="javascript" type="text/javascript"> var lblprice,ddlist,hidden; function Select1_onchange(seft,lblPrice,hd) { lblprice = lblPrice; ddlist = seft; hidden = hd; CurrencyService.GetCurrency(lblPrice,document.getElementById(hd).value,seft.value,Comple te,Error); } function Error(result) { ddlist.value = "USD"; alert("Vui lng th li sau"); } function Complete(result) { document.getElementById(lblprice).innerHTML= result; } </script> <uc1:Pager ID="bottomPager" runat="server" Visible="False" /> 6. chnh sa li file ProductsList.ascx.cs: using System; Lu hnh ni b Trang 483

using System.Collections; using System.Web.UI.WebControls; using System.Globalization; using CurrencyWS; public class MyCompareClass : IComparer { int IComparer.Compare(Object x, Object y) { return (string.Compare(x.ToString(), y.ToString())); } } public partial class UserControl_ProductsList : System.Web.UI.UserControl { private void InitializeComponent() { } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { InitCurrencyRate(); PopulateControls(); } } private void InitCurrencyRate() { if (Session["BookStoreCurrency"] == null) { hdRate.Value = "1"; ddlCurrency.SelectedIndex = 0; Session["BookStoreCurrency"] = "0,USD"; } else { string[] CurrencyInfo = (Session["BookStoreCurrency"].ToString()).Split(','); ddlCurrency.SelectedIndex = Int32.Parse(CurrencyInfo[0]); CurrencyConvertor currencyConvertor = new CurrencyConvertor(); if (CurrencyInfo[1] != "USD") try { hdRate.Value = (currencyConvertor.ConversionRate(Currency.USD, (Currency)Enum.Parse(typeof(Currency), CurrencyInfo[1]))).ToString(); } catch { ddlCurrency.SelectedIndex = 0; hdRate.Value = "1"; } else Lu hnh ni b Trang 484

hdRate.Value = "1"; } } private void PopulateControls() { string departmentId = Request.QueryString["DepartmentID"]; string categoryId = Request.QueryString["CategoryID"]; string page = Request.QueryString["Page"]; string searchString = Request.QueryString["Search"]; string dpId = Request.QueryString["dpid"]; if (page == null) page = "1"; int howManyPages = 1; string firstPageUrl = ""; string pagerFormat = ""; string currentpage = Request.AppRelativeCurrentExecutionFilePath; if (String.Compare(currentpage, "~/NewestProducts.aspx", true) == 0) { DateTime from = new DateTime(2009,10,1,12,0,0); list.DataSource = CatalogAccess.GetNewestProducts(from, DateTime.Now,OnlineStoreConfigurations.ProductDescriptionLength,Int32.Parse(page),Onlin eStoreConfigurations.ProductsPerPage,out howManyPages); list.DataBind(); firstPageUrl = LinkBuilder.ToNewestProducts("1"); pagerFormat = LinkBuilder.ToNewestProducts("{0}"); } else if (String.Compare(currentpage, "~/BestSellerProducts.aspx", true) == 0) { list.DataSource = CatalogAccess.GetBestSellerProducts(OnlineStoreConfigurations.ProductDescriptionLength, Int32.Parse(page), OnlineStoreConfigurations.ProductsPerPage, out howManyPages); list.DataBind(); firstPageUrl = LinkBuilder.ToBestSellerProducts("1"); pagerFormat = LinkBuilder.ToBestSellerProducts("{0}"); } else if (searchString != null) { string allWords = Request.QueryString["AllWords"]; list.DataSource = CatalogAccess.Search(searchString, dpId, Int32.Parse(page), OnlineStoreConfigurations.ProductsPerPage,out howManyPages); list.DataBind(); // Display pager firstPageUrl = LinkBuilder.ToSearch(searchString, dpId, "1"); pagerFormat = LinkBuilder.ToSearch(searchString, dpId, "{0}"); if (list.Items.Count == 0) lblError.Text = "Khng c sn phm no"; Lu hnh ni b Trang 485

} else if (categoryId != null) { list.DataSource = CatalogAccess.GetProductsInCategory(categoryId, page, out howManyPages); list.DataBind(); firstPageUrl = LinkBuilder.ToCategory(departmentId, categoryId, "1"); pagerFormat = LinkBuilder.ToCategory(departmentId, categoryId, "{0}"); } else if (departmentId != null) { list.DataSource = CatalogAccess.GetProductsOnDeptPromo(departmentId, page, out howManyPages); list.DataBind(); firstPageUrl = LinkBuilder.ToDepartment(departmentId, "1"); pagerFormat = LinkBuilder.ToDepartment(departmentId, "{0}"); } else { list.DataSource = CatalogAccess.GetProductsOnFrontPromo(page, out howManyPages); list.DataBind(); howManyPages = 1; } topPager.Show(int.Parse(page), howManyPages, firstPageUrl, pagerFormat, true); bottomPager.Show(int.Parse(page), howManyPages, firstPageUrl, pagerFormat, true); } protected void list_ItemCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e) { DataListItem items = e.Item; string productId = list.DataKeys[e.Item.ItemIndex].ToString(); ShoppingCartAccess.AddToShoppingCart(productId); Response.Redirect(Request.RawUrl); } public string FormatCurrency(double price) { NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat; return price.ToString("N",nfi); } protected void list_SelectedIndexChanged(object sender, EventArgs e) { } protected void list_ItemDataBound(object sender, DataListItemEventArgs e) { Lu hnh ni b Trang 486

Label lblPrice = e.Item.FindControl("lblPrice") as Label; HiddenField hd = e.Item.FindControl("hd") as HiddenField; NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat; double dprice = Double.Parse(hd.Value) * Double.Parse(hdRate.Value); lblPrice.Text = dprice.ToString("N", nfi) + " " + (Session["BookStoreCurrency"].ToString()).Split(',')[1]; //} } protected void ddlCurrency_SelectedIndexChanged(object sender, EventArgs e) { if (ddlCurrency.SelectedValue != "USD") { try { CurrencyConvertor currencyConvertor = new CurrencyConvertor(); hdRate.Value = (currencyConvertor.ConversionRate(Currency.USD, (Currency)Enum.Parse(typeof(Currency), ddlCurrency.SelectedValue))).ToString(); } catch { hdRate.Value = "1"; ddlCurrency.SelectedIndex = 0; lblError.Text = "C li trong qu trnh chuyn i, vui lng th li sau!"; } } else { hdRate.Value = "1"; } Session["BookStoreCurrency"] = ddlCurrency.SelectedIndex.ToString()+","+ddlCurrency.SelectedValue; PopulateControls(); Response.Redirect(Request.RawUrl); } } Mi khi ProductsList c load li s cn c vo query string ly c danh sch sn phm tng ng. Nh vy, khi mun load danh sch sn phm cho mt trang no trn website th ta ch cn s dng ProductsList User control ny.

Sau y l mt s giao din chnh ca website: Lu hnh ni b Trang 487

1. Trang ch trang ny ngi dng c th xem cc loi sch, ng nhp, ng k, tm kim

Thanh tm kim sch

Thng tin ng nhp

Service chuyn i tin t

Cc th loi sch chnh

Thng tin v sch nh tn sch, hnh nh, gi tin

Lu hnh ni b

Trang 488

2. Trang ng k Cho php ngi dng ng k mt ti khon c th s dng y cc chc nng ca trang web.

Cc thng tin cn thit khi ngi dng ng k ti khon

Lu hnh ni b

Trang 489

3. Trang ng nhp Ngi dng phi nhp chnh xc thng tin ti khon v mt khu.

Nu ngi dng ng nhp thnh cng.


Cho mng ti khon ng nhp thnh cng Trang qun l ti khon ca ngi dng

Thng tin v sch nh tn sch, hnh nh, gi tin

Lu hnh ni b

Trang 490

4. Trang cc loi sch Sch Khoa hc

Cc th loi sch con

Thng tin v sch thuc th loi Khoa Hc

Lu hnh ni b

Trang 491

5. Trang chi tit sn phm

Tn sch

Thm sn phm vo gi hng

Tm sn phm tng t trn Amazon

Tm sn phm tng t trn Ebay

Chuyn i tin t

Cc loi tin t c th chuyn i:

Lu hnh ni b

Trang 492

Nhng sn phm tng t trn Amazon

Lu hnh ni b

Trang 493

Nhng sn phm tng t trn Ebay

Lu hnh ni b

Trang 494

6. Trang qun l ti khon user

Lu hnh ni b

Trang 495

7. Trang gi hng

Tip tc qu trnh mua sch

Ti trang t hng

Lu hnh ni b

Trang 496

8. Trang t hng
Service chuyn i tin t

Chuyn ln trang PayPal thanh ton

Lu hnh ni b

Trang 497

9. Trang qun l

Cc thc n chc nng

Cc loi sch

Thm loi sch

Qun l n t hng

Lu hnh ni b

Trang 498

Cc ti liu tham kho 1. 2. 3. 4. 5. 6. 7. Gio trnh ngn ng C# Apress - Pro C# 2008 and the NET 3.5 Platform Fourth Edition K Thut Lp trnh C# Apress - Pro C# 2008 and the NET 3.5 Platform Fourth Edition Apress.Pro.LINQ.Language.Integrated.Query.in.C.Sharp.2008 Apress.Pro ASP.NET 3.5 in C# 2008 Lp trinh ASP.NET Tp 5.Quyn 3. Phm Hu Khang

Lu hnh ni b

Trang 499

You might also like