Introduction to ASP.docx
- 文档编号:14456921
- 上传时间:2023-06-23
- 格式:DOCX
- 页数:42
- 大小:376.74KB
Introduction to ASP.docx
《Introduction to ASP.docx》由会员分享,可在线阅读,更多相关《Introduction to ASP.docx(42页珍藏版)》请在冰点文库上搜索。
IntroductiontoASP
IntroductiontoASP.NETWebProgrammingUsingtheRazorSyntax(C#)
TheTop8ProgrammingTips
ThissectionlistsafewtipsthatyouabsolutelyneedtoknowasyoustartwritingASP.NETservercodeusingtheRazorsyntax.
Note TheRazorsyntaxisbasedontheC#programminglanguage,andthat'sthelanguagethat'susedmostoftenwithASP.NETWebPages.However,theRazorsyntaxalsosupportstheVisualBasiclanguage,andeverythingyouseeyoucanalsodoinVisualBasic.Fordetails,seetheappendixVisualBasicLanguageandSyntax.
Youcanfindmoredetailsaboutmostoftheseprogrammingtechniqueslaterinthearticle.
1.Youaddcodetoapageusingthe@character
The@characterstartsinlineexpressions,singlestatementblocks,andmulti-statementblocks:
--Singlestatementblocks-->
@{vartotal=7;}
@{varmyMessage="HelloWorld";}
--Inlineexpressions-->
Thevalueofyouraccountis:
@total
ThevalueofmyMessageis:
@myMessage
--Multi-statementblock-->
@{
vargreeting="Welcometooursite!
";
varweekDay=DateTime.Now.DayOfWeek;
vargreetingMessage=greeting+"Todayis:
"+weekDay;
}
Thegreetingis:
@greetingMessage
Thisiswhatthesestatementslooklikewhenthepagerunsinabrowser:
HTMLEncoding
Whenyoudisplaycontentinapageusingthe@character,asintheprecedingexamples,ASP.NETHTML-encodestheoutput.ThisreplacesreservedHTMLcharacters(suchas
IfyourgoalistooutputHTMLmarkupthatrenderstagsasmarkup(forexampleforaparagraphortoemphasizetext),seethesectionCombiningText,Markup,andCodeinCodeBlockslaterinthisarticle.
YoucanreadmoreaboutHTMLencodinginWorkingwithForms.
2.Youenclosecodeblocksinbraces
Acodeblockincludesoneormorecodestatementsandisenclosedinbraces.
--Singlestatementblock.-->
@{vartheMonth=DateTime.Now.Month;}
Thenumericvalueofthecurrentmonth:
@theMonth
--Multi-statementblock.-->
@{
varoutsideTemp=79;
varweatherMessage="Hello,itis"+outsideTemp+"degrees.";
}
Today'sweather:
@weatherMessage
Theresultdisplayedinabrowser:
3.Insideablock,youendeachcodestatementwithasemicolon
Insideacodeblock,eachcompletecodestatementmustendwithasemicolon.Inlineexpressionsdon'tendwithasemicolon.
--Single-statementblock-->
@{vartheMonth=DateTime.Now.Month;}
--Multi-statementblock-->
@{
varoutsideTemp=79;
varweatherMessage="Hello,itis"+outsideTemp+"degrees.";
}
--Inlineexpression,sonosemicolon-->
Today'sweather:
@weatherMessage
4.Youusevariablestostorevalues
Youcanstorevaluesinavariable,includingstrings,numbers,anddates,etc.Youcreateanewvariableusingthevarkeyword.Youcaninsertvariablevaluesdirectlyinapageusing@.
--Storingastring-->
@{varwelcomeMessage="Welcome,newmembers!
";}
@welcomeMessage
--Storingadate-->
@{varyear=DateTime.Now.Year;}
--Displayingavariable-->
Welcometoournewmemberswhojoinedin@year!
Theresultdisplayedinabrowser:
5.Youencloseliteralstringvaluesindoublequotationmarks
Astringisasequenceofcharactersthataretreatedastext.Tospecifyastring,youencloseitindoublequotationmarks:
@{varmyString="Thisisastringliteral";}
Ifthestringthatyouwanttodisplaycontainsabackslashcharacter(\)ordoublequotationmarks( " ),useaverbatimstringliteralthat'sprefixedwiththe@operator.(InC#,the\characterhasspecialmeaningunlessyouuseaverbatimstringliteral.)
--Embeddingabackslashinastring-->
@{varmyFilePath=@"C:
\MyFolder\";}
Thepathis:
@myFilePath
Toembeddoublequotationmarks,useaverbatimstringliteralandrepeatthequotationmarks:
--Embeddingdoublequotationmarksinastring-->
@{varmyQuote=@"Thepersonsaid:
""Hello,todayisMonday.""";}
@myQuote
Here'stheresultofusingbothoftheseexamplesinapage:
Note Noticethatthe@characterisusedbothtomarkverbatimstringliteralsinC#andtomarkcodeinASP.NETpages.
6.Codeiscasesensitive
InC#,keywords(likevar,true,andif)andvariablenamesarecasesensitive.Thefollowinglinesofcodecreatetwodifferentvariables,lastNameandLastName.
@{
varlastName="Smith";
varLastName="Jones";
}
IfyoudeclareavariableasvarlastName = "Smith";andifyoutrytoreferencethatvariableinyourpageas@LastName,anerrorresultsbecauseLastNamewon'tberecognized.
Note InVisualBasic,keywordsandvariablesarenotcasesensitive.
7.Muchofyourcodinginvolvesobjects
Anobjectrepresentsathingthatyoucanprogramwith—apage,atextbox,afile,animage,awebrequest,anemailmessage,acustomerrecord(databaserow),etc.Objectshavepropertiesthatdescribetheircharacteristicsandthatyoucanreadorchange—atextboxobjecthasaTextproperty(amongothers),arequestobjecthasaUrlproperty,anemailmessagehasaFromproperty,andacustomerobjecthasaFirstNameproperty.Objectsalsohavemethodsthatarethe"verbs"theycanperform.Examplesincludeafileobject'sSavemethod,animageobject'sRotatemethod,andanemailobject'sSendmethod.
You'lloftenworkwiththeRequestobject,whichgivesyouinformationlikethevaluesoftextboxes(formfields)onthepage,whattypeofbrowsermadetherequest,theURLofthepage,theuseridentity,etc.ThefollowingexampleshowshowtoaccesspropertiesoftheRequestobjectandhowtocalltheMapPathmethodoftheRequestobject,whichgivesyoutheabsolutepathofthepageontheserver:
Theresultdisplayedinabrowser:
8.Youcanwritecodethatmakesdecisions
Akeyfeatureofdynamicwebpagesisthatyoucandeterminewhattodobasedonconditions.Themostcommonwaytodothisiswiththeifstatement(andoptionalelsestatement).
@{
varresult="";
if(IsPost)
{
result="ThispagewaspostedusingtheSubmitbutton.";
}
else
{
result="Thiswasthefirstrequestforthispage.";
}
}
DOCTYPEhtml>
@result
Thestatementif(IsPost)isashorthandwayofwritingif(IsPost == true).Alongwithifstatements,thereareavarietyofwaystotestconditions,repeatblocksofcode,andsoon,whicharedescribedlaterinthisarticle.
Theresultdisplayedinabrowser(afterclickingSubmit):
HTTPGETandPOSTMethodsandtheIsPostProperty
Theprotocolusedforwebpages(HTTP)supportsaverylimitednumberofmethods(verbs)thatareusedtomakerequeststotheserver.ThetwomostcommononesareGET,whichisusedtoreadapage,andPOST,whichisusedtosubmitapage.Ingeneral,thefirsttimeauserrequestsapage,thepageisrequestedusingGET.Iftheuserfillsinaformandthenclicksasubmitbutton,thebrowsermakesaPOSTrequesttotheserver.
Inwebprogramming,it'softenusefultoknowwhetherapageisbeingrequestedasaGETorasaPOSTsothatyouknowhowtoprocessthepage.InASP.NETWebPages,youcanusetheIsPostpropertytoseewhetherarequestisaGEToraPOST.IftherequestisaPOST,theIsPostpropertywillreturntrue,andyoucandothingslikereadthevaluesoftextboxesonaform.Manyexamplesyou'llseeshowyouhowtoprocessthepagedifferentlydependingonthevalueofIsPost.
ASimpleCodeExample
Thisprocedureshowsyouhowtocreateapagethatillustratesbasicprogrammingtechniques.Intheexample,youcreateapagethatletsusersentertwonumbers,thenitaddsthemanddisplaystheresult.
1.Inyoureditor,createanewfileandnameitAddNumbers.cshtml.
2.Copythefollowingcodeandmarkupintothepage,replacinganythingalreadyinthepage.
@{
vartotal=0;
vartotalMessage="";
if(IsPost){
//Retrievethenumbersthattheuserentered.
varnum1=Request["text1"];
varnum2=Request["text2"];
//Converttheenteredstringsintointegersnumbersandadd.
total=num1.AsInt()+num2.AsInt();
totalMessage="Total="+total;
}
}
DOCTYPEhtml>
body{background-color:
beige;font-family:
Verdana,Arial;
margin:
50px;}
form{padding:
10px;border-style:
solid;width:
250px;}
EntertwowholenumbersandthenclickAdd.
@totalMessage