Vous êtes sur la page 1sur 23

Week 1 ASP.NET Web Forms Today Inspiration is wonderful when it happens but the writer must de!

elop an approa"h for the rest of the time. The wait is simply too lon#. $%eonard &ernstein In its early years the Web pushed an unusual pro#rammin# model and a set of pro#rammin# tools and lan#ua#es that were unknown or unfamiliar to the ma'ority of pro#rammers. Anybody who tried to build e!en a tri!ial Web site in the 1(()s had to "ome to #rips with the *T+% synta, and at least the simplest -a!aS"ript "ommands and ob'e"ts. That re.uired de!elopin# a brand new skill set whi"h for"ed people to ne#le"t other perhaps more produ"ti!e a"ti!ities. The "ode and user interfa"e of Web pa#es$sometimes referred to as the markup mi,$had to be written manually in the past de"ade. And this "reated a sort of tren"h separatin# die/hard 010221-a!a pro#rammers from freaky Web de!elopers. And a #rowin# number of de!elopers usin# +i"rosoft 3isual &asi" were left sittin# in the middle and in some way were kept from takin# a de"isi!e step in either dire"tion$whether it was toward 022 ser!er pro#rammin# or "lient Web pro#rammin#. +i"rosoft s"ored a remarkable !i"tory in the Web industry with the introdu"tion of the ASP.NET platform ba"k in 4))1. ASP.NET opened the doors of Web de!elopment to a hu#e number of professionals and "ontributed to "han#in# the de!elopment model of Web appli"ations. ASP.NET wasn5t alone in produ"in# this effort. ASP.NET followed up the pro#ress made by at least a "ouple of earlier te"hnolo#ies6 "lassi" A"ti!e Ser!er Pa#es 7ASP8 and -a!a Ser!er Pa#es 7-SP8.

The 9ri#inal Stren#ths The ASP.NET Web Forms model was ori#inally de!ised to brin# the power of :A; to the world of the Web. *en"e the .uest for produ"ti!ity was the primary dri!in# for"e behind most of the features that still represent the ma'or "hara"teristi"s and pillars of ASP.NET. There are three pillars to the Web Forms model6 pa#e postba"ks !iew state and ser!er "ontrols. They work to#ether a""ordin# to the model depi"ted in Fi#ure 1/1.

Ea"h *TTP re.uest that hits the Web ser!er and is mapped to the ASP.NET runtime #oes throu#h a number of sta#es "entered on the pro"essin# of the postba"k e!ent. The postba"k e!ent is the main a"tion that the user e,pe"ts out of her re.uest.

First the re.uest is pro"essed to e,tra"t preparatory information for the su""essi!e postba"k a"tion. Information in"ludes the state of "ontrols that alto#ether will produ"e the final *T+% for the pa#e. Followin# the postba"k the *T+% response is arran#ed for the browser in"ludin# the new state of "ontrols to be used upon the ne,t re.uest. All of the ser!er/side steps are wrapped up to#ether a""ordin# to the definition of the Pa#e 0ontroller pattern. In li#ht of this ea"h re.uest is seen as pro"essed by a "ontroller entity ultimately responsible for outputtin# an *T+% pa#e. The pa#e "ontroller entity is implemented as a "lass that fires a few e!ents in the de!eloper5s "ode thus #i!in# the de!eloper a way to intera"t with the re.uest and influen"e the final output. To better understand the sense of the Web Forms model and the reasons for its su""ess look at the followin# "ode snippet6 !oid &utton1<0li"k79b'e"t sender E!entAr#s ar#s8 = %abel1.Te,t > Te,t&o,1.Te,t? @ ;efined in a Web Forms "lass the &utton1<0li"k fun"tion represents the handler of a postba"k e!ent. When the user "li"ks the *T+% element with a mat"hin# I; 7in this "ase &utton18 a re.uest o""urs that is resol!ed by runnin# the "ode 'ust shown. If it weren5t for the stateless nature of the Web proto"ols this would be like the standard e!ent/dri!en pro#rammin# model that many of us used 7and en'oyed8 in the early 3isual &asi" days of the late 1(()s. In the body of the handler method you "an a""ess in a dire"t manner any other pa#e elements and set its state a""ordin#ly as if you were 'ust tou"hin# on the user interfa"e. Pa#e Postba"ks An ASP.NET pa#e is based on a sin#le form "omponent that "ontains all of the input elements the user "an intera"t with. The form "an also "ontain submission elements su"h as buttons or links. A form submission sends the "ontent of the "urrent form to a ser!er A:%$by default the same A:% of the "urrent pa#e. The a"tion of postin# "ontent ba"k to the same pa#e is known as the postba"k a"tion. In ASP.NET the pa#e submits any "ontent of its uni.ue form to itself. In other words the pa#e is a "onstituent blo"k of the appli"ation and "ontains both a !isual interfa"e and some lo#i" to pro"ess user #estures. The "li"k on a submit button or a link instru"ts the browser to re.uest a new instan"e of the same pa#e from the Web ser!er. In doin# so the browser also uploads any "ontent a!ailable in the 7sin#le8 pa#e5s form. 9n the ser!er the ASP.NET runtime en#ine pro"esses the re.uest and ends up e,e"utin# some "ode. The followin# "ode shows the link between the button "omponent and the handler "ode to run6 Basp6&utton runat>Cser!erC I;>C&utton1C 9n0li"k>C&utton1<0li"kC 1D The runnin# "ode is the ser!er/side handler of the ori#inal "lient/side e!ent. From within the handler the de!eloper "an update the user interfa"e by modifyin# the state of the ser!er "ontrols as already shown and as reiterated here6 publi" !oid &utton1<0li"k7ob'e"t sender E!entAr#s ar#s8 = 11 Sets the label to display the "ontent of the te,t bo, %abel1.Te,t > CThe te,tbo, "ontains6 C 2 Te,t&o,1.Te,t?

@ At the time the handler "ode runs any ser!er "ontrols on the pa#e ha!e been updated to hold e,a"tly the state they had durin# the last re.uest to the pa#e plus any modifi"ations resultin# from posted data. Su"h stateful beha!ior is lar#ely e,pe"ted in a desktop s"enario? in ASP.NET howe!er it re.uires the ma#i" of pa#e postba"ks.

The 3iew State The !iew state is a di"tionary that ASP.NET pa#es use to persist the state of their "hild "ontrols a"ross postba"ks. The !iew state plays an essential role in the implementation of the postba"k model. No statefulness would be possible in ASP.NET without the !iew state. &efore ASP.NET in "lassi" 3&S"ript/based ASP de!elopers fre.uently used hidden fields to tra"k "riti"al !alues a"ross two su""essi!e re.uests. This approa"h was ne"essary when multiple *T+% forms were used in the pa#e. Postin# from one would in fa"t reset any !alues in the fields within the other. To make up for this beha!ior the !alues to tra"k were stored in a hidden field and employed to pro#rammati"ally initialiEe fields durin# the renderin# of the pa#e. The !iew state is 'ust an en#ineered and e,tended !ersion of this "ommon tri"k. The !iew state is a uni.ue 7and en"oded8 hidden field that stores a di"tionary of !alues for all "ontrols in the 7uni.ue8 form of an ASP.NET pa#e. &y default ea"h pa#e "ontrol sa!es its entire state$all of its property !alues$to the !iew state. In an a!era#e/ siEed pa#e the !iew state takes up a few doEen F&s of e,tra data. This data is downloaded to the "lient and uploaded to the ser!er with e!ery re.uest for the pa#e. *owe!er it is ne!er used 7and should not be used8 on the "lient. The siEe of the !iew state has been si#nifi"antly redu"ed o!er the years but today the !iew state is still per"ei!ed as somethin# that has a hea!y impa"t on bandwidth.

Ser!er 0ontrols Ser!er "ontrols are "entral to the ASP.NET Web Forms model. The output of an ASP.NET pa#e is defined usin# a mi, of *T+% literals and markup for ASP.NET ser!er "ontrols. A ser!er "ontrol is a "omponent with a publi" interfa"e that "an be "onfi#ured usin# markup ta#s "hild ta#s and attributes. Ea"h ser!er "ontrol is "hara"teriEed by a uni.ue I; and is fully identified by that. In the ASP.NET pa#e markup the differen"e between a ser!er "ontrol and a plain *T+% literal strin# is the presen"e of the runat attribute. Anythin# in the sour"e de!oid of the runat attribute is treated as literal *T+% and is emitted to the output response stream as is. Anythin# fla##ed with the runat attribute is identified as a ser!er "ontrol.

The ;ata/for/;ata +odel For years the Web worked around a Pa#es/for/Forms model. It was 'ust fine in the be#innin# of the Web a#e when pa#es "ontained little more than formatted te,t hyperlinks and maybe some ima#es. The su""ess of the Web has prompted users to ask for in"reasin#ly more powerful features and it has led de!elopers and desi#ners to "reate more sophisti"ated ser!i"es and #raphi"s. As a result today5s pa#es are hea!y and "umbersome.

Gi!en the "urrent ar"hite"ture of Web appli"ations ea"h user a"tion re.uires a "omplete redraw of the pa#e. Subse.uently hea!ier pa#es render out slowly and produ"e a #ood deal of fli"kerin#. Pro'e"ted to the whole set of pa#es in a lar#e portal/like appli"ation this me"hanism is perfe"t for "ausin# #reat frustration to the poor end user. A-AH 'ust broke this model up. A re.uest mi#ht or mi#ht not post a form and re.uest an entire pa#e. +ore often an *TTP re.uest mi#ht 'ust pass raw data and re.uest raw data$an o!erall simplifi"ation of the intera"tion model. 7See Fi#ure 1/I.8

A-AH as a &uilt/in Feature of the Web Sele"ti!e Apdates &asi"ally there are two ways in whi"h you "an in"orporate A-AH into a Web framework. I like to refer to them as sele"ti!e updates and dire"t s"riptin#. Jou perform a sele"ti!e update when you e,e"ute a ser!er a"tion and then return a "hunk of *T+% to sele"ti!ely update the "urrent !iew. This approa"h des"ends from the *T+% +essa#e A-AH pattern as summariEed at http611a'a,patterns.or#. The tri"k is all in bypassin# the browser when a re.uest$ form post or hyperlink$has to be submitted. Jou pla"e a s"ript inter"eptor at the ;9+ le!el 7for e,ample a handler for the Form ;9+ ob'e"t submit e!ent8 "apture the on#oin# re.uest "an"el the operation and repla"e it with your own asyn"hronous implementation. When a response is re"ei!ed it is assumed to be *T+% and inte#rated into the "urrent ;9+ at a #i!en lo"ation.

;ire"t S"riptin# ;ire"t s"riptin# is plain -a!aS"ript "ode throu#h whi"h you "onne"t to a remote endpoint to send and re"ei!e data. Jou likely rely on a ri"h -a!aS"ript framework 7for e,ample 'Kuery8 and use the -S9N format to mo!e "omple, data around. ASP.NET +30 *i#hli#hts ASP.NET +30 is a "ompletely new framework for buildin# ASP.NET appli"ations desi#ned from the #round up with So0 and testability in mind. With ASP.NET +30 you redis"o!er the #ood old taste of the Web$stateless beha!ior full "ontrol o!er e!ery sin#le bit of *T+% and total s"ript and 0SS freedom. Pro"essin# the re.uest and #eneratin# the *T+% for the browser are distin"t steps and in!ol!e distin"t "omponents$the "ontroller and the !iew. The "ontroller #ets the re.uest and de"ides about the a"tion to take. The "ontroller #rabs the raw response and "ommuni"ates it to the !iew en#ine for the a"tual writin# onto the browser5s output stream . In ASP.NET +30 there5s no dependen"y on ASPH physi"al ser!er files. ASPH files mi#ht still be part of your pro'e"t but they now ser!e as plain *T+% templates that the default !iew en#ine uses as a template for "reatin# the *T+% response for the browser. When you author an ASP.NET +30 appli"ation you reason in terms of "ontrollers and a"tions. Ea"h re.uest must be mapped to a pair made by a "ontroller and an a"tion. E,e"utin# the a"tion produ"es data? the !iew en#ine #ets raw data and a template and produ"es the final markup 7or whate!er else it is e,pe"ted to produ"e su"h as -S9N or -a!aS"ript8. Fi#ure 1/L shows the se.uen"e of steps that "hara"teriEe a typi"al ASP.NET +30 re.uest.

As you "an see the run/time sta"k of ASP.NET +30 is simpler and the differen"e is due to the la"k of a pa#e life "y"le. As mentioned earlier the pa#e life "y"le and the entire thi"k abstra"tion layer built by Web Forms sa!es the de!eloper a lot of work. ASP.NET +30 is "loser to the metal and this has its own side effe"ts. If you need to maintain state that is up to you. For e,ample you "an store it into Session or 0a"he or you "an e!en "reate #uess what your own tailor/ made !iew stateMlike infrastru"ture. In the end the simpli"ity of ASP.NET +30 is due to different ar"hite"tural "hoi"es rather than to some o!erhead in the desi#n of the Web Forms model. So ASP.NET +30 brin#s to the table a "lean desi#n with a neat separation of "on"erns a leaner run/time sta"k full "ontrol o!er *T+% an unparalleled le!el of e,tensibility and a workin# en!ironment that enables not penaliEes test/dri!en de!elopment 7T;;8. 0ontrol o!er +arkup -ust like with Web Forms what some per"ei!e as a "lear stren#th of ASP.NET +30 others may see as a weakness. ASP.NET +30 doesn5t offer ser!er "ontrols of its own and also se!erely limits the use of "lassi" ASP.NET ser!er "ontrols. E!en thou#h you des"ribe the !iew of an ASP.NET +30 pa#e !ia ASPH markup you "an5t embed in it ser!er "ontrols that handle postba"ks. In other words you are allowed to use a ;ataGrid if your #oal is "reatin# a table of re"ords but your "ode will re"ei!e an e,"eption if the ;ataGrid is "onfi#ured to allow pa#in# sortin# or inline editin#.

To #ain full "ontrol o!er *T+% -a!aS"ript and 0SS ASP.NET +30 re.uires that you write Web elements manually one byte after the ne,t. This means that for the most part you are responsible for writin# e!ery sin#le BliDor BtableDta# you need. In ASP.NET +30 there5s no sort of "omponent model to help you with the #eneration of *T+%. As of today *T+% helpers and perhaps user "ontrols are the only tools you "an le!era#e to write *T+% more .ui"kly. 9!erall some de!elopers mi#ht see ASP.NET +30 as takin# a whole step ba"kward in terms of usability and produ"ti!ity.

ASP.NET Web Pa#es ASP.NET Web Forms was relati!ely easy to embra"e for de!elopers and software professionals. ASP.NET +30 re.uires a bit of e,tra work and doesn5t really lend itself to bein# learned and dis"o!ered on a trial/and/error basis. So how hi#h is the barrier to #et into the world of ASP.NETN Small Simple and Seamless ASP.NET Web Pa#es tar#ets an audien"e of Web de!elopers who are in!ol!ed in !ery simple pro'e"ts either be"ause they5re not software spe"ialists or be"ause the site to "reate is e,tremely simple indeed. This audien"e would benefit from e!en further simpli"ity su"h as a sin#le pa#e model and a simplified way of writin# "ode and the !iew. ASP.NET Web Pa#es "omes with a new I;E "alled Web+atri, and a simplified !ersion of IIS aptly named IIS E,press. Web+atri, in parti"ular wraps up ser!er "ode markup and database tables in a new desi#ner en!ironment that makes it a snap to write pa#es and publish them to a site. 0ode and 3iew To#ether With ASP.NET Web Pa#es you write pa#es usin# a mi,ed synta, that in"orporates both markup and "ode but in a way that is a bit "leaner than today with either Web Forms or ASP.NET +30 "ode blo"ks. &y usin# the O,,, synta, where ,,, is a built/in ob'e"t you "an insert in the markup some dynami"ally "al"ulated !alue and also use those "omponents to emit ad ho" markup. *ere5s an e,ample6 BbodyD Today is O;ateTime.Now B1bodyD Week 4 INT:9;A0TI9N T9 SE:3E: 09NT:9%S It5s important to understand how ser!er "ontrols operate and how they are "ompletely different from the way you define "ontrols in other lan#ua#es like "lassi" ASP or P*P 7another popular pro#rammin# lan#ua#e for "reatin# dynami" websites8. For e,ample to influen"e the te,t in a te,t bo, in these lan#ua#es you would use plain *T+% and mi, it with ser!er/side "ode. To "reate a te,t bo, with a messa#e and the "urrent time in it in "lassi" ASP you "an use the followin# "ode6 Binput type>Cte,tC !alue>C*ello World the time is BP>Time78PDC 1D As you "an see this "ode "ontains plain *T+% mi,ed with a ser!er/side blo"k delimited by BPand PDthat outputs the "urrent time usin# the e.uals 7>8 symbol. This type of "odin# has a ma'or disad!anta#e6 the *T+% and ser!er/side "ode is mi,ed makin# it diffi"ult to write and maintain your pa#es. Althou#h this is a tri!ial e,ample in whi"h it5s still easy to understand the "ode this type of pro#rammin# "an .ui"kly result in !ery messy and "omple, pa#es.

Ser!er "ontrols work differently. In ASP.NET the "ontrols Qli!eR on the ser!er inside an ASPH pa#e. When the pa#e is re.uested in the browser the ser!er/side "ontrols are pro"essed by the ASP.NET run time$the en#ine that is responsible for pro"essin# re.uests for ASPH pa#es. The "ontrols then emit "lient/side *T+% "ode that is appended to the final pa#e output. It5s this *T+% "ode that e!entually ends up in the browser where it5s used to build up the pa#e.So instead of definin# *T+% "ontrols in your pa#es dire"tly you define an ASP.NET Ser!er 0ontrol with the followin# synta, where the itali"iEed parts differ for ea"h "ontrol6 Basp6Type9f0ontrolI;>C0ontrolNameC runat>Cser!erC 1D For the "ontrols that ship with ASP.NET S.T you always use the asp6 prefi, followed by the name of the "ontrol. For e,ample to "reate a Te,t&o, that "an hold the same wel"ome messa#e and "urrent time you "an use the followin# synta,6 Basp6Te,t&o, I;>C+essa#eC runat>Cser!erC 1D Note that the "ontrol has two attributes6 I; and runat. The I; attribute is used to uni.uely identify a "ontrol on the pa#e so you "an pro#ram a#ainst it. It5s important that ea"h "ontrol on the pa#e has a uni.ue I;? otherwise the ASP.NET run time won5t understand what "ontrol you5re referrin# to. If you a""identally type a dupli"ate "ontrol I; 3S si#nals the problem in the error list. The mandatory runat attribute is used to indi"ate that this is a "ontrol that li!es on the ser!er. Without this attribute the "ontrols won5t be pro"essed and will end up dire"tly in the *T+% sour"e. If you e!er feel you5re missin# a "ontrol in the final output in the browser ensure that the "ontrol has this re.uired attribute. Note that for non/ser!er elements like plain *T+% elements the runat attribute is optional. With this attribute non/ser!er "ontrols "an be rea"hed by your pro#rammin# "ode. Jou "an easily add the runat attribute to an e,istin# element usin# a "ode snippet by typin# runat and pressin# the Tab key.The pre"edin# e,ample of the Te,t&o, uses a self/"losin# ta# where the "losin# slash 718 is embedded in the openin# ta#. This is .uite "ommon for "ontrols that don5t need to "ontain "hild "ontent su"h as te,t or other "ontrols. *owe!er the lon# !ersion usin# a separate "losin# ta# is a""eptable as well6 Basp6Te,t&o, I;>C+essa#eC runat>Cser!erCDB1asp6Te,t&o,D 0U +essa#e.Te,t > C*ello World the time is C 2 ;ateTime.Now.Time9f;ay.ToStrin#78? The definition of the "ontrol in the markup se"tion of the pa#e is now separated from the a"tual "ode that defines the te,t displayed in the te,t bo, makin# it easier to define and pro#ram the te,t bo, 7or any other "ontrol8 be"ause it enables you to fo"us on one task at a time. Jou "an either de"lare the "ontrol and its !isual appearan"e in the markup se"tion of the pa#e or pro#ram its beha!ior from a "ode blo"k. As its name implies an ASP.NET Ser!er 0ontrol li!es on the ser!er in your ASPH pa#e where it "an be pro"essed by the ASP.NET run time. When you re.uest a pa#e in the browser the run time "reates an in/memory representation of the ASPH file with the "ontrols you "reated. When the run time is about to send the *T+% to the browser it asks ea"h of the "ontrols in the pa#e for their *T+% whi"h is then in'e"ted in the final response. For e,ample when the %abel "ontrol is asked for its *T+% the first time it loads it returns the followin#6 Bspan id>C:esultCDB1spanD Althou#h you defined the %abel "ontrol with the Basp6%abelD synta, it ends up as a simple BspanDelement in the browser. &e"ause the Te,t property of the %abel "ontrol is empty you don5t see any te,t between the two BspanDta#s. The same applies to other "ontrols? an Basp6Te,t&o,Dends up as Binput type>Cte,tCD whereas the Basp6&uttonD ends up as Binput type>CsubmitCD. When you "li"k the button the "ontrol "auses a postba"k whi"h sends the information for the "ontrols in the pa#e to the ser!er where the pa#e is loaded a#ain. Additionally the "ode that you wrote to handle the button5s 0li"k

e!ent is e,e"uted. This "ode takes the name you entered in the te,t bo, and then assi#ns it to the %abel "ontrol as shown in this 0U e,ample6 :esult.Te,t > CJour name is C 2 JourName.Te,t?

Standard 0ontrols The Standard "ate#ory "ontains many of the basi" "ontrols that almost any web pa#e needs. some of them are Te,t&o, &utton and %abel "ontrols. Simple 0ontrols The Toolbo, "ontains a number of simple and strai#htforward "ontrols in"ludin# Te,t&o, &utton %abel *yper%ink :adio&utton and 0he"k&o,. Their i"ons in the Toolbo, #i!e you a #ood "lue as to how they end up in the browser. %ist 0ontrols Basp6;rop;own%ist I;>CFa!orite%an#ua#eC runat>Cser!erCD Basp6%istItem 3alue>C0UCD0UB1asp6%istItemD Basp6%istItem 3alue>C3isual &asi"CD3isual &asi"B1asp6%istItemD Basp6%istItem 3alue>C0SSCD0SSB1asp6%istItemD B1asp6;rop;own%istD The standard "ate#ory also "ontains a number of "ontrols that present themsel!es as lists in the browser. These "ontrols in"lude %ist&o, ;rop;own%ist 0he"k&o,%ist :adio&utton%ist and &ulleted%ist. To add items to the list you define Basp6%istItemD elements between the openin# and "losin# ta#s of the "ontrol.The ;rop;own%ist enables a user to sele"t only one item at a time. To see the "urrently a"ti!e and sele"ted item of a list "ontrol pro#rammati"ally you "an look at its Sele"ted3alue Sele"tedItem or Sele"tedInde, properties. Sele"ted3alue returns a strin# that "ontains the !alue for the sele"ted item like 0U or 3isual &asi" in the pre"edin# e,ample. Sele"tedInde, returns the Eero/based inde, of the item in the list. With the pre"edin# e,ample if the user had "hosen 0U Sele"tedInde, would be ). Similarly if the user had "hosen 0SS the inde, would be 4 7the third item in the list8. For "ontrols that allow multiple sele"tions 7like 0he"k&o,%ist and %ist&o,8 you "an loop throu#h the Items "olle"tion and see what items are sele"ted. In this "ase Sele"tedItem returns only the first sele"ted item in the list? not all of them. Note that in the browser both the ;rop;own%ist and the %ist&o,"ontrol render as a Bsele"tD element. Attributes su"h as siEe and multiple set by these two "ontrols determine the appearan"e and beha!ior of the *T+% element in the browser. The &ulleted%ist "ontrol doesn5t allow a user to make sele"tions and as su"h doesn5t support these properties. 0ontainer 0ontrols Kuite often it5s desirable to #roup related "ontent and "ontrols. Jou "an do this by puttin# the "ontrols 7and other markup8 in one of the "ontainer "ontrols like the Panel the Pla"e*older the +ulti3iew or the WiEard. For e,ample you "an use the Pla"e*olderor the Panel"ontrol to hide or show a number of "ontrols at on"e. Instead of hidin# ea"h "ontrol separately you simply hide the entire "ontainer that "ontains all the indi!idual "ontrols and markup. &oth of these "ontrols ha!e their own ad!anta#es and disad!anta#es. The #ood thin# about the Pla"e*older "ontrol is that it emits no *T+% of its own into the pa#e so you "an use it as a "ontainer without any side effe"ts in the final pa#e. *owe!er it la"ks desi#n/time support makin# it hard to mana#e the "ontrols inside the Pla"e*older at desi#n time in 3S. In "ontrast the Panel enables you to easily a""ess all "on/trols and other

"ontent it "ontains but renders itself as a Bdi!Delement. In many "ases this isn5t a problem and "an e!en be useful as you "an tar#et that di! usin# 0SS at the "lient so usually you5re best off with the Panel "ontrol be"ause of its desi#n/time support. The +ulti3iew7whi"h "an "ontain one or more Basp63iewD elements8 and the WiEard are similar in that they enable you to split up a lon# pa#e into multiple areas makin# it easy to fill in a lon# form for e,ample. The WiEard has built/in support for mo!in# from pa#e to pa#e usin# Pre!ious Ne,t and Finish buttons whereas the +ulti3iew must be "ontrolled pro#rammati"ally. 0ommon Properties for All 0ontrols +ost of the ser!er "ontrols you find in the 3S Toolbo, share some "ommon beha!ior. Part of this beha!ior in"ludes the so/"alled properties that define the data a "ontrol "an "ontain and e,pose. Ea"h ser!er "ontrol has an I; to uni.uely identify it in the pa#e a runat attribute that is always set to ser!er to indi"ate the "ontrol should be pro"essed on the ser!er and a 0lientI; that "ontains the "lient/side I; attribute that is assi#ned to the element in the final *T+%. In !ersions of ASP.NET up to V.T this 0lientI; was always #enerated for you automati"ally. *owe!er in ASP.NET S a new 0lientI;+ode property was introdu"ed that #i!es you more "ontrol o!er the I; of an element at the "lient. The runat attribute is te"hni"ally not a property of a ser!er "ontrol but is ne"essary to indi"ate that the markup for the "ontrol should be pro"essed as a ser!er "ontrol and not end up as plainte,t or *T+% in the browser.

%ink&utton and Ima#e&utton The %ink&utton and the Ima#e&utton "ontrols operate similarly to an ordinary &utton "ontrol. &oth of them "ause a postba"k to the ser!er when they are "li"ked. The %ink&utton presents itself as a simple BaD element but posts ba"k 7usin# -a!aS"ript8 instead of re.uestin# a new pa#e. The Ima#e&utton does the same but displays an ima#e that the user "an "li"k to tri##er the postba"k. Ima#e and Ima#e+ap

These "ontrols are pretty similar in that they display an ima#e in the browser. The Ima#e+ap enables you to define hotspots on the ima#e that when "li"ked either "ause a postba"k to the ser!er or na!i#ate to a different pa#e. 0alendar The 0alendar "ontrol presents a ri"h interfa"e that enables a user to sele"t a date. FileApload The FileApload "ontrol enables a user to upload files that "an be stored on the ser!er. %iteral %o"aliEe and Substitute All three "ontrols look a little like the %abel "ontrol be"ause they "an all display stati" te,t or *T+%. The bi##est ad!anta#e of the %iteral is that it renders no additional ta# itself? it displays only what you assi#n to its Te,t property and is thus !ery useful to display *T+% or -a!aS"ript that you build up in the 0ode &ehind or that you retrie!e from a database. The %o"aliEe "ontrol is used in multilin#ual websites and is able to retrie!e its "ontents from translated resour"e files. The Substitute "ontrol is used in ad!an"ed "a"hin# s"enarios and enables you to update only parts of a pa#e that is otherwise "a"hed "ompletely. Ad:otator The Ad:otator "ontrol enables you to display random ad!ertisements on your website. The ads "ome from an H+% file that you "reate on your ser!er. &e"ause it la"ks ad!an"ed features like "li"k tra"kin# and lo##in# that are re.uired in most but the simplest s"enarios this "ontrol isn5t used mu"h in today5s websites. *iddenField The *iddenField "ontrol enables you to store data in the pa#e that is submitted with ea"h re.uest. This is useful if you want the pa#e to remember spe"ifi" data without the user seein# it on the pa#e. &e"ause the field does show up in the *T+% sour"e of the pa#e and is thus a""essible to the end user you should ne!er store any sensiti!e data in it. H+% The H+% "ontrol enables you to transform data from an H+% format to another format 7like H*T+%8 for display on a pa#e. Table The Basp6TableD "ontrol is in many respe"ts identi"al to its *T+% BtableD"ounterpart. *owe!er be"ause the "ontrol li!es at the ser!er you "an pro#ram a#ainst it "reatin# new "olumns and rows dynami"ally and addin# dynami" data to it.

*T+% 0ontrols The *T+% "ate#ory of the Toolbo, "ontains a number of *T+% "ontrols that look similar to the ones found in the Standard "ate#ory. For e,ample you find the Input 7&utton8 that looks like the Basp6&uttonD. Similarly there is a Sele"t "ontrol that has the Basp6;rop;own%istD and Basp6%ist&o,D as its "ounterparts. In "ontrast to the ASP.NET Ser!er 0ontrols the *T+% "ontrols are "lient/side "ontrols and end up dire"tly in the final *T+% in the browser. Jou "an e,pose them to ser!er/side "ode by addin# a runat>Cser!erC attribute to them. This enables you to pro#ram a#ainst them from the 0ode &ehind of a Web Form to influen"e thin#s like their !isibility.

The *T+% "ontrols ha!e a lot less fun"tionality than the ones in the Standard "ate#ory. For e,ample the Sele"t "ontrol la"ks desi#n/time support for addin# new items to the list with the %istItem 0olle"tion Editor. This for"es you to write the items by hand in the +arkup 3iew of 3S.

T*E ASP.NET STATE ENGINE What Is State and Why Is It ImportantN To understand state it5s important to realiEe that by desi#n *TTP$the proto"ol used to re.uest and ser!e pa#es in a web browser$is stateless. What this means is that the web ser!er does not keep tra"k of re.uests that ha!e been made from a spe"ifi" browser. As far as the web ser!er is "on"erned ea"h re.uest you make to the ser!er by browsin# to a pa#e and "li"kin# links to other pa#es stands on its own. The web ser!er has no re"olle"tion of pa#es you re.uested pre!iously. This poses some interestin# problems. 0onsider for e,ample a simple lo#in pa#e that enables you to lo# in to a website like your fa!orite web mail pro#ram. Now ima#ine that you try to lo# in with a "orre"t username but with an in"orre"t password. The pa#e will then inform you that your lo#in attempt failed. Ideally you would also want your username to be filled in for you automati"ally and you5d want the :emember +e Ne,t Time "he"k bo, to retain its sele"tion as well. That way it5s easy for the user to enter the "orre"t password and "li"k the %o# In button a#ain. This is 'ust a tri!ial e,ample but it5s easy to "ome up with many more s"enarios where it5s useful if "ontrols are able to maintain their own state. *owe!er by default a web pa#e or a "ontrol "annot do this on its own. &e"ause ea"h re.uest is a standalone re.uest the ser!er won5t fill in the te,t bo,es a#ain after a postba"k but will simply ser!e the pa#e the same way it did when it first loaded it. In other web te"hnolo#ies like "lassi" ASP or P*P you "ould work around this by manually writin# "ode that prepopulates "ontrols after a postba"k. Fortunately ASP.NET makes this mu"h easier for you by inte#ratin# this fun"tionality in the ASP.NET feature set. *ow the State En#ine Works The state en#ine in ASP.NET is "apable of storin# state for many "ontrols. It "an store state not only for user input "ontrols like a Te,t&o, and a 0he"k&o, but for other "ontrols like a %abel and e!en a 0alendar.

The App<0ode Folder The App<0ode folder is a spe"ial ASP.NET folder. It5s desi#ned spe"ifi "ally to hold "ode files like "lasses that you5ll use throu#hout the site. 0ode that applies only to one pa#e 7like the handler of a &utton "ontrol5s 0li"k e!ent8 should remain in the pa#e5s 0ode &ehind as you ha!e seen so far. With the App<0ode folder in pla"e you "an start addin# "lass files to it. 0lass files ha!e an e,tension that mat"hes the pro#rammin# lan#ua#e you ha!e "hosen for the site6 ."s for 0U files and .!b for files "ontainin# 3&.NET "ode. Inside these "lass files you "an "reate "lasses that in turn "ontain methods 7fun"tions and subroutines8 that "an "arry out "ommon tasks.

0ommentin# 0ode Inline Inline "omments are written dire"tly in between your "ode statements. Jou "an use them to "omment on e,istin# !ariables diffi"ult loops and so on. In 3&.NET you "an "omment out only one line at a time usin# the ti"k 7W8 "hara"ter whi"h you pla"e in front of the te,t that you want to use as a "omment. To "omment a sin#le line in 0U you use two slashes 7118. Additionally you "an use 1Xand X1 to "omment out an entire blo"k of "ode in 0U. The followin# e,amples show some different uses of "omments6 11 Asa#e6 "omment out "ode thatWs not used 7anymore8. 11 In this e,ample SomeAnfinished+ethod is "ommented out

11 to pre!ent it from bein# e,e"uted. 11 SomeAnfinished+ethod78? 11 Asa#e6 End of line "omments. if 7Aser.IsIn:ole7CAdministratorsC88 11 9nly allow admins in this area =@ 1X X This is a blo"k of "omments that is often used to add additional X information to your "ode for e,ample to e,plain a diffi"ult loop. Jou "an X also use this to 7temporarily8 "omment a whole blo"k of "ode. X1

Important 99 Terminolo#y 9b'e"ts 9b'e"ts are the basi" buildin# blo"ks of ob'e"t/oriented pro#rammin# lan#ua#es. -ust like in the real world an ob'e"t in 99/land is a thin# but stored in the "omputer5s memory. 0al"ulator my0al"ulator > new 0al"ulator78? int a#e > new int78? &e"ause it5s so "ommon to "reate !ariables of simple types like int and strin# the "ompiler allows you to lea!e out the new keyword and the assi#nment. 0lasses 0lasses are the blueprints of ob'e"ts. -ust as you "an use a sin#le blueprint to build a bun"h of similar houses you "an use a sin#le "lass to "reate multiple instan"es of that "lass. So the "lass a"ts as the definition of the ob'e"ts that you use in your appli"ation. publi" "lass 0lassName = @ &e"ause this "ode simply defines an empty "lass it "annot do anythin# useful. To #i!e the "lass some beha!ior you "an #i!e it fields properties methods and "onstru"tors.

Fields Fields are simple !ariables de"lared at the "lass le!el that "an "ontain data. They are often used as ba"kin# !ariables for properties. publi" "lass Person = pri!ate strin# <firstName? @ Fields are often marked as pri!ate whi"h makes them !isible only in the "lass that defines them.

Properties

Properties of an ob'e"t are the "hara"teristi"s the ob'e"t has. 0onsider a Person ob'e"t. Jou define a property in a "lass with a property header similar to a method in 0U. Jou use a #et blo"k and a set blo"k to define the so/"alled #etters and setters of the property. The #etter is a""essed when an ob'e"t is asked for the !alue of a spe"ifi" property and the setter is used to assi#n a !alue to the property. Properties only pro!ide a""ess to underlyin# data stored in the ob'e"t? they don5t "ontain the a"tual data. To store the data you need what is "alled a ba"kin# !ariable. This is often a simple field defined in the "lass that is able to store the !alue for the e,ternal property.

publi" "lass Person = pri!ate strin# <firstName? publi" strin# FirstName = #et = return <firstName? @ set = <firstName > !alue? @ @ @ It is "ommon to prefi, the pri!ate ba"kin# !ariables with an unders"ore followed by the first word in all lower"ase optionally followed by more words that start with a "apital a#ain. So the FirstName property has a ba"kin# !ariable "alled <firstName %astName has one "alled <lastName and so on. This way all !ariables that apply to the entire "lass are ni"ely pa"ked to#ether in the IntelliSense list. Simply type an unders"ore in your "ode and you5ll #et the full list of pri!ate !ariables. The main reason for a property in a "lass is to en"apsulate data. The idea is that a property enables you to "ontrol the data that is bein# assi#ned to it. This way you "an perform !alidation or manipulation of the data before it5s stored in the underlyin# ba"kin# !ariable. set = if 7Ystrin#.IsNull9rEmpty7!alue88 = <firstName > !alue.Substrin#7) 18.ToApper78 2 !alue.Substrin#718? @ else = <firstName > strin#.Empty? @ @ The "ode first "he"ks if the !alue that is bein# passed is not null in and that it doesn5t "ontain an empty strin# usin# the handy Strin#.IsNull9rEmpty method. The "ode in the If blo"k then takes the first letter of !alue usin# the Substrin# method of the Strin# "lass to whi"h it passes the !alues ) and 1. The ) indi"ates the start of the substrin# and the 1 indi"ates the len#th of the strin# that must be returned. Strin# inde,in# is Eero/based as well so a start of ) and a len#th of 1 effe"ti!ely returns the first "hara"ter of the !alue parameter. This "hara"ter is then "han#ed to upper"ase usin# ToApper78. Finally the "ode takes the remainder of the !alue parameter usin# Substrin# a#ain and assi#ns the "ombined name ba"k to the ba"kin# !ariable. In this "all to Substrin# only the start inde, is passed whi"h returns the strin# from that position to the end. For simple properties that don5t need any data manipulation or !alidation you "an use so/"alled automati" properties. With these properties you "an use a mu"h more "ondensed synta, without the need for a pri!ate ba"kin# !ariable. When the "ode is "ompiled the "ompiler "reates a hidden ba"kin# !ariable for you and you5ll need to refer to the publi" property. *ere5s the ;ate9f&irth property of the Person "lass written as an automati" property6 publi" ;ateTime ;ate9f&irth = #et? set? @

Week V 09NSISTENT PAGE %AJ9AT WIT* +ASTE: PAGES The bi##est benefit of master pa#es is that they enable you to define the look and feel of all the pa#es in your site in a sin#le lo"ation. This means that if you want to "han#e the layout of your site$for instan"e if you want to mo!e the menu from the left to the ri#ht$you need to modify only the master pa#e and the pa#es based on this master pi"k up the "han#es automati"ally. To some e,tent a master pa#e looks like a normal ASPH pa#e. It "ontains stati" *T+% su"h as the BhtmlD BheadD and BbodyDelements and it "an also "ontain other *T+% and ASP.NET Ser!er 0ontrols. Inside the master pa#e you set up the markup that you want to repeat on e!ery pa#e like the #eneral stru"ture of the pa#e and the menu. *owe!er a master pa#e is not a true ASPH pa#e and "annot be re.uested in the browser dire"tly? it only ser!es as the template on whi"h real web pa#es$"alled content pages$are based. A master pa#e uses an O+aster dire"ti!e that identifies the file as a master pa#e6 BPO +aster %an#ua#e>C0UC PD -ust like a normal ASPH pa#e a master pa#e "an ha!e a 0ode &ehind file identified by its 0ode File and Inherits attributes6 To "reate re#ions that "ontent pa#es "an fill in you define 0ontentPla"e*older "ontrols in your pa#e like this6 Basp60ontentPla"e*older I;>C0ontentPla"e*older1C runat>Cser!erCD B1asp60ontentPla"e*olderD Jou "an "reate as many pla"eholders as you like althou#h you usually need only a few to "reate a fle,ible pa#e layout.

Introdu"tion to the ASP.NET Pa#e %ife 0y"le When you think about how a pa#e is ser!ed by a web ser!er to the browser and think of this pro"ess as the life "y"le of a pa#e you "an probably "ome up with a few important moments in the pa#e5s life.

Anderstandin# Absolute and :elati!e A:%s Fey to workin# with links in your site is a #ood understandin# of the different forms a uniform resour"e lo"ator 7A:%8 to a resour"e inside or outside your website "an take. A A:% is used to uni.uely identify a resour"e in your or another website. These A:%s are used in different pla"es in"ludin# the href attribute of a hyperlink or a BlinkDelement to point to a 0SS file the sr" attribute pointin# to an ima#e or a -a!aS"ript sour"e file and the url78 !alue of a 0SS property. A A:% "an be e,pressed as a relati!e A:% or an absolute A:%. &oth ha!e ad!anta#es and disad!anta#es that you should be aware of. 9ne benefit of relati!e A:%s is that you "an mo!e a set of files to another dire"tory at the same le!el without breakin# their internal links. *owe!er at the same time they make it more diffi"ult to mo!e files to a different le!el in the site hierar"hy. For e,ample if you mo!ed the %o#in.asp, pa#e to a separate folder like +embers the link to the +ana#ement folder would break. The new +embers folder doesn5t ha!e +ana#ement as its subfolder so +ana#ement1;efault.asp, is no lon#er a !alid link. To o!er"ome this problem you "an use root/based relati!e A:%s.

0reatin# Aser 0ontrols Aser "ontrols are #reat for en"apsulatin# markup "ontrols and "ode that you need repeatedly throu#hout your site. To some e,tent they look a bit like ser!er "ontrols in that they "an "ontain pro#rammin# lo#i" and

presentation that you "an reuse in your pa#es. *owe!er rather than dra##in# e,istin# ones from the 3S Toolbo, you need to "reate your own user "ontrols and then add them to your ASPH pa#es. Thou#h master pa#es enable you to "reate "ontent that is displayed in all pa#es in your site it5s "ommon to ha!e "ontent that should appear only on some but not all pa#es. For e,ample you may want to display a banner on a few popular pa#es but not on the homepa#e or other "ommon pa#es. Without user "ontrols you would add the "ode for the banner 7an ima#e a link and so on8 to ea"h pa#e that needs it. When you want to update the banner 7if you want to use a new ima#e or link8 you need to make "han#es to all pa#es that use it. If you mo!e the banner to a user "ontrol and use that "ontrol in your "ontent pa#es instead all you need to "han#e is the user "ontrol and the pa#es that use it pi"k up the "han#e automati"ally. This #i!es you a fle,ible way to "reate reusable "ontent. Aser "ontrols ha!e the followin# similarities with normal ASPH pa#es6 They ha!e a markup se"tion where you "an add standard markup ser!er "ontrols and plain *T+%. They "an be "reated and desi#ned with 3isual Studio in +arkup ;esi#n and Split 3iew. They "an "ontain pro#rammin# lo#i" either inline or with a 0ode &ehind file. They #i!e you a""ess to pa#e/based information like :e.uest.KueryStrin#. They raise some 7but not all8 of the e!ents that the Pa#e "lass raises in"ludin# Init %oad and Pre:ender.

Jou should also be aware of a few differen"es. Aser "ontrols ha!e an .as", e,tension instead of the re#ular .asp, e,tension. In addition user "ontrols "annot be re.uested in the browser dire"tly. Therefore you "an5t link to them. The only way to use a user "ontrol in your site is by addin# it to a "ontent or master pa#e or another user "ontrol 7whi"h e!entually should be added to a pa#e8. 3alidatin# Aser Input ASP.NET 3alidation 0ontrols ASP.NET S.T "omes with si, useful "ontrols to perform !alidation in your website. Fi!e of them are used to perform the a"tual !alidation whereas the final "ontrol$3alidationSummary$is used to pro!ide feedba"k to the user about any errors made in the pa#e. The !alidation "ontrols are e,tremely helpful in !alidatin# the data that a user enters in the system. They "an easily be hooked to other "ontrols like the Te,t&o, or a ;rop;own%ist? howe!er they also support "ustom !alidation s"enarios. The #reat thin# about the !alidation "ontrols is that they "an "he"k the input at the "lient and at the ser!er. When you add a !alidation "ontrol to a web pa#e the "ontrol renders -a!aS"ript that !alidates the asso"iated "ontrol at the "lient. This "lient/side !alidation works on most modern web browsers with -a!aS"ript enabled. Althou#h "lient/side !alidation may seem enou#h to pre!ent users from sendin# in!alid data to your system you should ne!er rely on it as the only solution to !alidation. It5s easy to disable -a!aS"ript in the browser renderin# the "lient/side !alidation routines useless. In addition a mali"ious user "an easily bypass the entire pa#e in the browser and send information dire"tly to the ser!er whi"h will happily a""ept and pro"ess it if you don5t take "ountermeasures. Asin# the 3alidation 0ontrols To de"lare a !alidation "ontrol in your ASPH pa#e you use the familiar de"larati!e synta,. For e,ample to "reate the :e.uiredField3alidator"ontrol used in Fi#ure (/4 you need the followin# "ode6
Basp6:e.uiredField3alidator I;>C:e.3al1C runat>Cser!erC 0ontrolTo3alidate>CJourNameC Error+essa#e>CEnter your nameC 1D

The 0ontrolTo3alidate property links this !alidation "ontrol to another "ontrol in the pa#e. When asked to perform its !alidation the !alidation "ontrol looks at the !alue of the linked "ontrol and when that !alue doesn5t meet the !alidation rules you set it displays the messa#e set in the Error+essa#e property by default althou#h you "an o!erride this beha!iour. With the :e.uiredField3alidator atta"hed to the "ontrol throu#h the 0ontrolTo3alidate property "lient/side -a!aS"ript is sent to the browser that !alidates the "ontrol at the "lient. The :e.uiredField3alidator "ontrol is able to !alidate another "ontrol. It does this by "omparin# the !alue of the other "ontrol with its own Initial3alue property and makin# sure that the other "ontrol5s !alue is different. &y

default this property is an empty strin# whi"h means that anythin# e,"ept an empty strin# is "onsidered a !alid !alue. Whene!er you try to submit the form to the ser!er by "li"kin# the Send button the !alidation "ontrol "he"ks the "ontrol it is atta"hed to. The Standard 3alidation 0ontrols The fi!e !alidation "ontrols 7the ones in the 3alidation "ate#ory of the Toolbo, whose names end in 3alidator8 ultimately all inherit from the same base "lass and thus share some "ommon beha!ior. Four of the fi!e !alidation "ontrols operate in the same way and "ontain built/in beha!ior that enables you to !alidate asso"iated "ontrols. The last "ontrol the 0ustom3alidator enables you to write "ustom !alidation rules not supported out of the bo,. The ;ifferen"e between the Te,t and Error+essa#e Properties At first #lan"e these two properties seem to ser!e the same purpose. &oth of them "an be used to pro!ide feedba"k to the user in the form of an error messa#e. &ut when used in "ombination with a 3alidationSummary "ontrol there5s a subtle differen"e between the two. When you set both the properties at the same time the !alidation "ontrol displays the Te,t property whereas the 3alidationSummary uses the Error+essa#e. :an#e3alidator The :an#e3alidator "ontrol enables you to "he"k whether a !alue falls within a "ertain ran#e. The "ontrol is able to "he"k data types like strin#s numbers dates and "urren"ies. For e,ample you "an use it to make sure a number is between 1 and 1) a "hara"ter between A and F or a sele"ted date falls between today and the ne,t two weeks. The followin# table lists its most important properties.

The followin# e,ample shows a :an#e3alidator that ensures that the !alue entered in the :ate te,tbo, is a whole number that lies between 1 and 1)6
Basp6:an#e3alidator I;>C:an#e3alidator1C runat>Cser!erC 0ontrolTo3alidate>C:ateC Error+essa#e>CEnter a number between 1 and 1)C +a,imum3alue>C1)C +inimum3alue>C1C Type>CInte#erC 1D

:e#ularE,pression3alidator The :e#ularE,pression3alidator "ontrol enables you to "he"k a !alue a#ainst a re#ular e,pression that you set in the 3alidationE,pression property of the "ontrol. :e#ular e,pressions offer a "ompa"t synta, that enables you to sear"h for patterns in te,t strin#s. :e#ular e,pressions are a "omple, sub'e"t but fortunately 3isual Studio "omes with a few built/in e,pressions that make it easy to !alidate !alues like e/mail addresses and ZIP "odes. The followin# e,ample shows a :e#ularE,pression3alidator "ontrol that ensures that a user enters a !alue that looks like an e/mail address6
Basp6:e#ularE,pression3alidator I;>C:e#ularE,pression3alidator1C runat>Cser!erC 0ontrolTo3alidate>CEmailC Error+essa#e>CEnter a !alid e/mail addressC 3alidationE,pression>C[w27\/2.W][w28XO[w27\/.][w28X[.[w27\/.][w28XC 1D

0ompare3alidator The 0ompare3alidator "an be used to "ompare the !alue of one "ontrol to another !alue. This is often used in si#n/up forms where users ha!e to enter a password twi"e to make sure they type the same password both times.

This e,ample shows a 0ompare3alidator that ensures that two Te,t&o, "ontrols "ontain the same password6
Basp60ompare3alidator I;>C0ompare3alidator1C runat>Cser!erC 0ontrolTo0ompare>C0onfirmPasswordC 0ontrolTo3alidate>CPasswordC Error+essa#e>CJour passwords donWt mat"hC 1D

-ust like the :e.uiredField3alidator "ontrol the other !alidation "ontrols emit -a!aS"ript to the "lient whi"h is tri##ered when you "li"k the Send button or when the !alue of one of the "lient "ontrols is "han#ed. The 0ompare3alidator works by lookin# at the !alue of two different "ontrols. 9nly when both "ontain the same data will it return true. It5s important to realiEe that the 0ompare3alidator "ontrol does not tri##er its !alidation "ode when the te,t bo,es are empty. Therefore it5s important to hook up a :e.uiredField3alidator "ontrol as well. This "ontrol first makes sure the user entered at least some data and then the 0ompare3alidator "ontrol ensures that the te,t is the same in both te,t bo,es. The :e#ularE,pression3alidator "ontrol works by "he"kin# the pattern of the data that it is !alidatin#. If you look at the 3alidationE,pression property of the "ontrol you see a lon# "rypti" strin#. This pattern ensures that the e/ mail address "ontains some te,t optionally followed by some separation "hara"ter like a dash 7/8 or period followed by more te,t. It also ensures that there5s an O symbol in the address followed by a domain name a period and then at least one more "hara"ter to represent the top/le!el domain like ."om .nl or ."o.uk. With this e,pression youOe,ample."omis "onsidered a !alid e/mail address. So is aOa.a whereas youOyou isn5t. Note that the :e#ularE,pression3alidator "ontrol only rou#hly "he"ks the synta, of the e/mail address. It5s still perfe"tly possible to enter a none,istent e/mail address that 'ust looks !alid or e!en an in!alid e/mail address su"h as aOa.a. *owe!er in many "ases this !alidator is #ood enou#h to filter out "ommon typos that users make when enterin# e/mail addresses. The 0ustom3alidator "ontrol enables you to write "ustom !alidation fun"tions for both the "lient 7in -a!aS"ript8 and the ser!er 7usin# 3&.NET or 0U8. This #i!es you #reat fle,ibility with re#ard to the data you want to !alidate and the rules you want to apply. The 3alidationSummary "ontrol pro!ides the user with a list of errors that it retrie!es from the indi!idual !alidation "ontrol5s Error+essa#eproperties. It "an display these errors in three different ways6 usin# a list embedded in the pa#e usin# a -a!aS"ript alert bo, or usin# both at the same time. Jou "ontrol this settin# with the Show+essa#e&o, and ShowSummary properties. Additionally the ;isplay+ode property enables you to "han#e the way the list of errors is presented. The default settin# is &ullet%ist where ea"h error is an item in a bulleted list but other options are %ist7without bullets8 and Sin#lePara#raph. Week S ;isplayin# ;ata ;ATA 09NT:9%S

To enable you to work effi"iently with the data in your system ASP.NET offers two sets of data/aware "ontrols6 the data/bound "ontrols and the data sour"e "ontrols. The first #roup "ontains "ontrols that you use to display and edit data su"h as the Grid3iew :epeater and %ist3iew "ontrols in the user interfa"e. The data sour"e "ontrols are used to retrie!e data from a data sour"e like a database or an H+% file and then offer this data to the data/bound "ontrols. Fi#ure 1V/1 shows the "omplete list of a!ailable data "ontrols in the ;ata "ate#ory of the Toolbo,.

;ata/&ound 0ontrols Se!en of the "ontrols in the Toolbo, depi"ted in Fi#ure 1V/1 are the so "alled data/bound "ontrols. Jou use them to display and edit data on your web pa#es. The Grid3iew ;ata%ist %ist3iew and :epeater are all able to display multiple rows at the same time. As su"h they are often referred to as list "ontrols. The ;etails3iew and the Form3iew are desi#ned to show a sin#le row at a time. The ;ataPa#er is a helper "ontrol used to pro!ide pa#in# "apabilities to the %ist3iew "ontrols. %ist 0ontrols &e"ause ASP.NET offers multiple "ontrols to display lists of rows you may be wonderin# when to "hoose what "ontrol. The Grid3iew is a !ery !ersatile "ontrol that supports automati" pa#in# 7where rows are spread out o!er multiple Qpa#esR8 sortin# editin# deletin# and sele"tin#. It renders its data like a spreadsheet with rows and "olumns. Althou#h many possibilities e,ist to style the looks of these rows and "ontrols you "annot radi"ally "han#e the way the data is presented. Additionally the Grid3iew does not allow you to insert rows in the underlyin# data sour"e dire"tly.

The ;ata%ist "ontrol enables you to present data not only in rows as with the Grid3iew but in "olumns as well enablin# you to "reate a matri,/like presentation of data. The "ontrol "an be "onsidered depre"ated and is repla"ed with the %ist3iew whi"h is a lot more powerful. The :epeater #i!es you the #reatest fle,ibility in terms of the *T+% that you output to the browser be"ause the "ontrol by itself does not add any *T+% to the pa#e output. As su"h it5s often used for *T+% ordered or unordered lists 7BolD and BulD8 and other lists where you "an5t affordo ha!e unwanted *T+% mi,ed with your own. Jou define the entire "lient markup throu#h the numerous templates the "ontrol e,poses. *owe!er this fle,ibility "omes at a pri"e6 the "ontrol has no built/in "apabilities to pa#e sort or modify data. The %ist3iew was introdu"ed in ASP.NET V.T and is a best/of/all/worlds "ombination of the Grid3iew the ;ata%ist and the :epeater. The "ontrol supports editin# deletin# and pa#in# of data similar to the Grid3iew. It supports multi/"olumn and multi/row layouts like the ;ata%ist offers and it enables you to "ompletely "ontrol the markup #enerated by the "ontrol 'ust as the :epeater does. It also supports insertin# and updatin# data like the ;etails3iew or Form3iew"ontrols. In ASP.NET S list "ontrols were e,tended with a 0lientI;:owSuffi, property that enables you to indi"ate the "olumn whose !alue is used to "reate uni.ue "lient/side I;s based on data in the database.

Sin#le Item 0ontrols The ;etails3iew and Form3iew "ontrols are somewhat similar in that both of them "an display a sin#le re"ord at a time. The ;etails3iew uses a built/in tabular format to display the data whereas the Form3iew uses templates to let you define the look and feel of your data. A simple template/based ;etails3iew "ould look like the one shown in Fi#ure 1V/V.

The Form3iew "ontrol and a few of the %o#in "ontrols ha!e a :ender9uterTable property. When you set this property to False7it defaults to True so you need to set it e,pli"itly8 the "ontrol doesn5t #enerate a wrappin# *T+% BtableD element. This in turn results in less "ode and "leaner *T+%. &oth "ontrols enable you to define the templates for different situations su"h as a read/only display of data and insertin# and updatin# of data. Pa#in# 0ontrols Another useful "ontrol is the ;ataPa#er whi"h enables pa#in# on other "ontrols. For the time bein# you "an only use it to e,tend the %ist3iew"ontrol but that mi#ht "han#e with future !ersions of the .NET Framework. For the data/bound "ontrols to display somethin# useful you need to assi#n them a data sour"e. To bind this data sour"e to the "ontrols two main methods are a!ailable6 Jou "an assi#n data to the "ontrol5s ;ataSour"e property or you "an use one of the separate data sour"e "ontrols. ;ata Sour"e 0ontrols The ;ata "ate#ory of the Toolbo, "ontains si, different data sour"e "ontrols that you "an use to bind data to your data/bound "ontrols. The Hml;ataSour"e and Site+ap;ataSour"e "ontrols are used to bind hierar"hi"al H+%/ based data to these "ontrols. The 9b'e"t;ataSour"e "ontrol enables you to "onne"t your data/bound "ontrols to separate ob'e"ts in your appli"ation. Instead of tyin# your data/aware "ontrols dire"tly to a database you bind data from a separate layer with "ustom ob'e"ts to them. The final three data sour"e "ontrols are the S.l;ataSour"e the Entity;ataSour"e and the %in.;ataSour"e "ontrols. The %in.;ataSour"e ser!es as a data sour"e for %INK to SK% a te"hnolo#y similar to the A;9.NET Entity Framework. The KueryE,tender "ontrol a"ts like an add/on to the %in.;ataSour"e and Entity;ataSour"e "ontrols in that it enables you to "reate a ri"h filterin# interfa"e to sear"h for spe"ifi" data without manually writin# a lot of "ode. The S.l;ataSour"e "ontrol enables you to .ui"kly "reate fun"tional database/dri!en web pa#es. Without writin# a whole lot of "ode you "an "reate web pa#es that enable you to perform all four operations of the 0:A; a"ronym6 0reate :ead Apdate and ;elete data. Althou#h its name may seem to imply that the "ontrol "an a""ess only +i"rosoft5s SK% Ser!er that5s not the "ase. The "ontrol "an a""ess other databases su"h as 9ra"le or +ySK% as well.
Accessing Data using System.Data The System.Data namespace provides access to classes that represent the ADO.NET architecture. ADO.NET lets you build components that efficiently manage data from multiple data sources. In a disconnected scenario such as the Internet, ADO.NET provides the tools to re uest, update, and reconcile data in multiple tier systems. The ADO.NET architecture is also implemented in client applications, such as !indo"s #orms, or $T%& pages created by AS'.NET.

The centerpiece of the ADO.NET architecture is the DataSet class. A DataSet represents an in(memory cache of data.Each DataSet can contain multiple DataTable ob)ects, "ith each DataTable containing data from a single data source, such as S*& Server. A DataTable represents one table of in( memory data. +sing the System.Data.S l,lient namespace -the.NET #rame"or. Data 'rovider for S*& Server/, the System.Data.Odbc namespace -the.NET #rame"or. Data 'rovider for OD0,/, the System.Data.OleDb namespace -the.NET #rame"or. Data 'rovider for O&E D0/, or the System.Data.Oracle,lient namespace -the .NET #rame"or. Data 'rovider for Oracle/, you can access a data source to use together "ith a DataSet. Each.NET #rame"or. data provider has a corresponding DataAdapter that you use as a bridge bet"een a data source and a DataSet. The GridView allo"s for a number of different types of columns, 1 The BoundField, "hich displays the value of specified DataSource field as te2t. -This is the type of column used by default "hen tying

a GridView to a DataSourcethrough the Smart Tag interface./ The ImageField, "hich displays an image based on an image path in a specified DataSource field. -!e sa" an e2ample of using this column type in the previous e2ercise./

Another useful column type is the Template#ield, "hich allo"s for a mi2 of $T%& mar.up, !eb controls, and data(binding synta2. One common use of a Template#ield is to perform custom logic to massage the output3 another common use is to embed other !eb controls "ithin a GridView column. Repeater The 4epeater control is used to display a repeated list of items that are bound to the control. The 4epeater control may be bound to a database table, an 5%& file, or another list of items. The contents of the 6$eaderTemplate7 element are rendered first and only once "ithin the output, then the contents of the 6ItemTemplate7 element are repeated for each 8record8 in the DataSet, and last, the contents of the 6#ooterTemplate7 element are rendered once "ithin the output1 6asp14epeater id98cdcatalog8 runat98server87 6$eaderTemplate7 ... 6:$eaderTemplate7 6ItemTemplate7 ... 6:ItemTemplate7 6#ooterTemplate7 ... 6:#ooterTemplate7 6:asp14epeater7 6AlternatingItemTemplate7 ;ou can add an 6AlternatingItemTemplate7 element after the 6ItemTemplate7 element to describe the appearance of alternating ro"s of output. 6SeparatorTemplate7 The 6SeparatorTemplate7 element can be used to describe a separator bet"een each record.

+i"rosoft ;ata :eport ;esi#ner


The +i"rosoft ;ata :eport desi#ner is a !ersatile data report #enerator that features the ability to "reated banded hierar"hi"al reports. Ased in "on'un"tion with a data sour"e su"h as the ;ata En!ironment desi#ner you "an "reate reports from se!eral different relational tables. In addition to "reatin# printable reports you "an also e,port the report to *T+% or te,t files.

Possible Uses
Automati"ally "reate reports that are e,ported in *T+% format for instant distribution on the Internet. 0reate reports that show the sums of transa"tions o""urrin# on a daily basis.

Data Report Designer Features


The ;ata :eport desi#ner has se!eral features6 1. Drag-and-Drop Functionality for Fields$;ra# fields from the +i"rosoft ;ata En!ironment desi#ner to the ;ata :eport desi#ner. When you do this 3isual &asi" automati"ally "reates a te,t bo, "ontrol on the data report and sets the ;ata+ember and ;ataField properties of the dropped field. Jou "an also dra# a 0ommand ob'e"t from the ;ata En!ironment desi#ner to the ;ata :eport desi#ner. In that "ase for ea"h of the fields "ontained by the 0ommand ob'e"t a te,t bo, "ontrol will be "reated on the data report? the ;ata+ember and ;ataField property for ea"h te,t bo, will be set to the appropriate !alues. 4. Toolbox Controls$The ;ata :eport desi#ner features its own set of "ontrols. When a ;ata :eport desi#ner is added to a pro'e"t the "ontrols are automati"ally "reated on a new Toolbo, tab named ;ata:eport. +ost of the "ontrols are fun"tionally identi"al to 3isual &asi" intrinsi" "ontrols and in"lude a %abel Shape Ima#e Te,t&o, and %ine "ontrol. The si,th "ontrol the Fun"tion "ontrol automati"ally #enerates one of four kinds of information6 Sum A!era#e +inimum or +a,imum. For more information about the Fun"tion "ontrol see CAddin# a Fun"tion 0ontrol to the ;ata :eport.C V. Print Preview$Pre!iew the report by usin# the Show method. The data report is then #enerated and displayed in its own window. Note A printer must be installed on the "omputer to show the report in print pre!iew mode. S. Print Reports$Print a report pro#rammati"ally by "allin# the Print:eport method. When the data report is in pre!iew mode users "an also print by "li"kin# the printer i"on on the toolbar. Note A printer must be installed on the "omputer to print a report. T. File Export$E,port the data report information usin# the E,port:eport method. Formats for e,port in"lude *T+% and te,t. I. Export Te plates$Jou "an "reate a "olle"tion of file templates to be used with the E,port:eport method. This is useful for e,portin# reports in a !ariety of formats ea"h tailored to the report type. L. !sync"onous #peration$The ;ata:eport ob'e"tWs Print:eport and E,port:eport methods are asyn"hronous operations. Asin# the Pro"essin#Timeout e!ent you "an monitor the state of these operations and "an"el any that are takin# too lon#.

Vous aimerez peut-être aussi