关闭

关闭

关闭

封号提示

内容

首页 ASP.NET MVC in Action.pdf

ASP.NET MVC in Action.pdf

ASP.NET MVC in Action.pdf

于庆-甲寅 2010-12-18 评分 0 浏览量 0 0 0 0 暂无简介 简介 举报

简介:本文档为《ASP.NET MVC in Actionpdf》,可适用于IT/计算机领域,主题内容包含MEAPEditionManningEarlyAccessProgramCopyrightManningPublicationsFormoreinf符等。

MEAPEditionManningEarlyAccessProgramCopyrightManningPublicationsFormoreinformationonthisandotherManningtitlesgotowwwmanningcomContentsPrefaceChapter:GettingstartedwiththeASPNETMVCFrameworkChapter:TheModelindepthChapter:TheControllerindepthChapter:ViewsindepthChapter:RoutingChapter:CustomizingandextendingtheASPNETMVCFrameworkChapter:ScalingthearchitecturetomorecomplexsitesChapter:LeveragingexistingASPNETfeaturesChapter:AJAXinASPNETMVCChapter:HostinganddeploymentChapter:ExploringMonoRailandRubyonRailsChapter:BestpracticesChapter:RecipesGettingStartedwiththeASPNETMVCFrameworkThischapterincludes:ƒSystemrequirementsforusingtheASPNETMVCFrameworkƒRunningthestarterprojectƒProgressive“HelloWorld”examplesƒStronglytypedviewsƒRoutingbasicsDependingonhowlongyou’vebeenbuildingwebapplicationsontheMicrosoftplatform,you’llrelatetosomeorallofthefollowingpainInthe’s,developersbuiltinteractivewebsitesusingexecutableprogramsthatranonaserverTheseprograms(CGIwasacommontechnologyatthetime)acceptedawebrequestandwereresponsibleforcreatinganHTMLresponseTemplatingwasadhoc,andtheprogramsweredifficulttowrite,debugandtestInthelate’s,Microsoft,afterabriefstintwithHTXtemplatesandIDCconnectors,introducedActiveServerPages,orASPActiveServerPagesbroughttemplatingtowebapplicationsTheserverpagewasanHTMLdocumentwithdynamicscriptmixedinWhilethiswasabigstepforwardfromthealternatives,theworldsoonsawmassiveserverpageswithcodeindecipherablefromthemarkupInearly,alongcameASPNETASPNETwasacompleteshiftforASPdevelopersbecauseitmovedallserverpagecodeintoaclassfileandreplacedtheHTMLmarkupwithdynamicservercontrolsinanXMLsyntaxWhileperformanceincreased,andthedebuggingexperienceimproved,newproblemsaroseTheserversidepostbackeventlifecyclecausednewsgroupstoexplodewithactivityasdevelopersearchedforthemagiceventinwhichtoaddthosetwosimplelinesofcodenecessarytomakethepageworkasneededViewState,whilegoodintheory,brokedownastheapplicationscaledwithcomplexitySimplepagesbrokeKBinsize,mostofwhichwastheViewStatePerhapsthegreatestsinoftheASPNETframeworkwasthetightcouplingtoeverythingintheSystemWebnamespaceTherewasnohopeofunittestinganycodeinthecodebehindfile,andtodayweseePageLoadmethodsthattakeseveraltreestoprintWhileearlyversionsofASPNEThadsomedrawbacks,ASPNET,andthelargerNetFramework,hasmadehugeinroadsintothewebapplicationmarketTodayweseemajorwebsitessuchasCallawayGolfcom,Dellcom,NewsweekcomandMatchcomallrunningonASPNETTheplatformhasprovenitselfinthemarketplace,and,whencombinedwithIISrunningonWindows,ASPNETcaneasilysupportcomplexwebapplicationsrunninginverylargedatacentersThisnextversionofASPNETleveragesitspastandbuildsonitssuccessestopropelASPNETfurtherforwardasaleaderinthewebspaceTheASPNETMVCFrameworkhasbeenintroducedtosimplifythecomplexpartsofWebFormswhileretainingthepowerandflexibilityoftheASPNETpipelineTheadvantagesoftheASPNETrequestpipelineandinfrastructurestaythesame,andASPNETMVCisprovidedtosupportASPNETapplicationsusingtheModelViewControllerpresentationpatternControllingcodeiskeptinaclassseparatedfromharddependencies,andserverpageshavemorphedintosimpleviews,whicharenothingmorethanHTMLtemplatesfilledinwithobjectspassedinbythecontrollerThepostbackeventlifecycleisnomore,andViewStateisnolongernecessaryInthischapter,wewillwalkthroughyourfirstlinesofcodebuiltontopoftheASPNETMVCFrameworkAfterthisprimer,youwillbereadyformoreadvancedtopicsThroughoutthischapter,wewilltakeyouthroughcreatinganewASPNETMVCFrameworkwebapplicationproject,creatingyourfirstroutes,controllers,andviewsWewillcombthroughthedefaultapplicationandexplaineachpartThenwewillextendit,andyouwillcreateyourfirstcontrollerandviewBeforethefirstexample,letusexploretheMVCpatternandthedefaultapplicationtemplateprovidedwiththeframeworkPickingAparttheDefaultApplicationInthissection,wewillunderstandwhattheMVCpatternisandcreateourfirstASPNETMVCWebApplicationWewillfocusfirstonthecontrollerbecauseintheModelViewControllertriad,thecontrollerisinchargeanddecideswhatmodelobjectstouseandwhatviewstorenderThecontrollerisinchargeofcoordinationandexecutesfirstwhenthewebrequestcomesintotheapplicationThecontrollerisresponsiblefordecidingwhatresponseisappropriatefortherequestTheModelViewControllerpatternisnotnewInfact,itisquiteoldAcoretenetoftheMVCpatternistoseparatecontrollogicfromtheview,orascreenAviewisresponsibleforrenderingtheuserinterfaceByseparatingdomainlogicanddecouplingdataaccessandothercallsfromtheview,theuserinterfacecannowstaythesameevenwhilelogicanddataaccesschangeswithintheapplicationInfigure,youwillseeasimplediagramofthemodelviewcontrollertriadNotethatthecontrollerhasadirectrelationshipwiththeviewandthemodel,butthemodeldoesnotneedtoknowaboutthecontrollerortheviewThewebrequestwillbehandledbythecontroller,andthecontrollerwilldecidewhichmodelobjectstouseandwhichviewobjectstorenderFigureAsimplediagramdepictingtherelationshipbetweentheModel,View,andControllerNote:thesolidlinesindicateadirectassociation,andthedashedlinesindicateanindirectassociation(graphicanddescriptionusedwithpermissionfromWikipedia)Tobegin,wewillopenupVisualStudioSPandcreateourprojectTheeditionofVisualStudiomakessomedifferenceWhiletherearesomeworkaroundstousingtheASPNETMVCFrameworkwithoutSP,SystemWebAbstractionsdllandSystemWebRoutingdllareintheGACasofSPYoucanuseVisualStudioProfessional,aTeamEditionsku,orVisualWebDeveloperExpressSPItisveryimportanttonotethattheASPNETMVCFrameworkbuildsontopofwebapplicationprojects,andwhileitispossibletomakeitworkwithWebSites,thedevelopmentexperienceisoptimizedforusewithWebApplicationProjectsNOTE:YoumustalreadyhavetheMVCFrameworkinstalledtoproceedTheMVCFrameworkisanindependentreleasethatbuildsonNetServicePackYoucanalsodeployyourapplicationbyincludingtheMVCFrameworkassembliesinthebinfolderofyourwebapplicationifyouneedtorunonaserverwithonlyNetSPinstalledIfyouarefondofRedGate'sNetReflector:http:wwwredgatecomproductsreflector),youwanttobesuretofamiliarizeyourselfwiththeSystemWebMvcnamespaceintheSystemWebMvcassemblyTheexamplesinthisbookwilluseVisualStudioSP,butyoucanfindinformationonusingVisualWebDeveloperExpressSPontheASPNETMVCwebsite:http:wwwaspnetmvcWe'llbegininVisualStudioProfessionalSPbycreatinganewASPNETMVCWebApplicationprojectWhenyoupulluptheNewProjectdialog,makesureyouhaveNetFrameworkselectedIfyouhaveNetFrameworkorselected,VisualStudiowillfilterthelist,andyouwillnotseetheprojecttemplateforASPNETMVCWebApplicationNowthatyouunderstandthebasicsofthepatternandhowtoinstalltheMVCframework,wewilldiveintoourfirstprojectCreatingtheProjectCreatingyourfirstASPNETMVCWebApplicationprojectwillbeoneofthesimplestthingsyoudoasyoumovethroughthischapterInVisualStudio,whenyouhaveNETFrameworkselectedasthetargetframework,youwillseeanewprojecttemplatenamed“ASPNETMVCWebApplication”ThisistheprojecttemplateyouwillwanttochooseThenewprojectdialogwilllooklikethatshowninfigureFigureTheMVCWebApplicationprojectisaprojecttemplateaddedtotheC#andVBNetsectionsoftheNewProjectdialogItisonlyavailablewhenyouhaveNetFrameworkselectedasthetargetframeworkWearegoingtobeworkingwithaC#ASPNETMVCWebApplicationprojectYouhavetwooptionsforcreatingtheprojectWhenyouclickOK,theIDEwillaskyouaboutcreatingatestprojectItisuptoyouifyouwouldlikeitdoneforyouorifyouwouldrathercreatetheunittestprojectyourselfIfyouarejuststartingout,makesureyoucreateaunittestprojectalongwithyourwebprojectIfyouhaveanexistingsolutionandyouareaddingtheASPNETMVCWebApplication,youmaychoosetoonlyaddoneprojectandthenaddaClassLibraryprojectimmediatelyafterwardtosupporttheunittestsForthisexample,wewillmoveforwardandchoosetheASPNETMVCWebApplicationwiththetestprojectFigureshowsthesolutionstructureofthedefaultVisualStudiotemplateSincethisisnotabeginners’book,wewillskipthehandholdingandgostraightintotheprojectNOTE:MoreASPNETMVCsolutiontemplatesareavailablethroughtheNetcommunityAtthetimeofwriting,http:CommunityForMvcnethadseveralsolutiontemplatesforASPNETMVCapplicationsSomeoftheoptionsinclude:oMinimalsolutionwithveryfewextrasoSolutioncompletewithMvcContrib,StructureMap,NHibernate,NUnit,NAnt,AutoMapper,Tarantino,Naak,NBehave,RhinoMocks,WatiN,Gallio,Castle,zip,etcIfyouarenewtoNetdevelopmentingeneral,getfamiliarwithMicrosoft'ssolutiontemplatefirstThenuseamorerobustsolutiontemplateprovidedbythecommunitytohaveabetterjumpingoffpointWhenyouhavemasteredtheframework,thinkaboutcontributingyourownsolutiontemplatesFigureThedefaultstructureforawebapplicationprojectusingtheASPNETMVCFrameworkusesconventionfortheplacementoffilesThefirstthingyouwillnoticeisthattheprojectcomeswithafewconventionsFirst,thereisafolder,andbyconvention,namespace,forcontrollersandviewsYouwillalsoseeafoldercalled“Models”Thisisforview(orpresentation)modelclassesForanynontrivialsystem,youwillwanttohaveaprojectthatcontainsyourdomainmodelSomeexamplesavailableontheInternethavethedomainmodelinthewebapplicationproject,butifyouintendtohaveyournontrivialapplicationhavealonglife,werecommendyouputonlypresentationconcernsinthewebapplicationprojectLastly,inthedefaultproject,youwillbefamiliarwiththeDefaultaspxfilethatisprovidedforyou,andwe'lldiscussshortlywhythatisthereFirst,wemustunderstandtheconceptofarouteYourFirstRoutesRouteswillbediscussedingreatdetailinchapterhowever,youshouldbeawareofsomeroutebasicstomovethroughthissectionWhilepreviousversionsofASPNETmandatedastrictconventionforURLs,theMVCframeworkprovidesamechanismtohandcraftURLsThisconceptiscalledroutingRoutingwasreleasedintoASPNETintheNetFrameworkServicePack,andisavailabletoallASPNETapplications,notjustthosebuiltwiththeMVCframeworkTheGlobalasaxcsfilecontainssomeroutesthatareprovidedwiththeMVCWebApplicationprojectBeforecontinuing,wemustdefinewhatarouteisArouteisthecompletedefinitionforhowtohandleawebrequestthroughtheSystemWebMvcMvcRouteHandlerWithWebForms,wehavelittlecontroloverthiswithoutresortingtoURLrewritingWithWebForms,theURLofthewebrequestistightlycoupledtothepagehandlingtherequestIfthepagewasnamedFooaspxinafoldernamedSamples,thentheURLwassuretobehttp:MvcContriborgSamplesFooaspxManyteamshaveresortedtoURLrewritingtowranglesomecontrolovertheURLsandhowtheyareproducedWiththeASPNETMVCFramework,andASPNETSPingeneral,routesarefirstclasscitizensinthewebapplicationWestartwithdefininghowwewantourURLsstructuredTheprojecttemplategivesusafewroutestostart,showninListingListingDefaultroutesforanewprojectTheseareaddedbytheprojecttemplateusingSystemWebusingSystemWebMvcusingSystemWebRoutingnamespaceChGettingStarted{Note:ForinstructionsonenablingIISorIISclassicmode,visithttp:gomicrosoftcomLinkId=GlobalasaxcspublicclassMvcApplication:HttpApplication{publicstaticvoidRegisterRoutes(RouteCollectionroutes){routesIgnoreRoute("{resource}axd{*pathInfo}")routesMapRoute("Default",Routename"{controller}{action}{id}",URLwithparametersnew{controller="Home",action="Index",id=""}Parameterdefaults)}protectedvoidApplicationStart(){RegisterRoutes(RouteTableRoutes)}}}Routesneedtobedefinedasoneofthefirstthingswhenthewebapplicationstartsup,sotheprojecttemplateaddstheroutestotheApplicationStartmethodintheGlobalasaxcsfileLaterinthebook,you'llseethatwedonotleavetheroutesinthislocationexceptforthemosttrivialofwebapplicationsNOTEWewillfollowlongstandingbestpracticesofSeparationofConcernsandtheSingleResponsibilityPrinciple,orSRP,bymovingtheroutestoadedicationlocationseparatedbyaninterfaceWe'llgomoreintotheseprincipleslater,but,inshort,theresponsibility(orconcern)oftheApplicationStartmethodistokickoffoperationsthatmusthappenatthebeginningoftheapplication'slifeTheresponsibilityisnottoperformeverybitofworkthatmusthappenonstartAnyoperationsthatmusthappenonwhentheapplicationstartsshouldresideinseparateclassesandmerelybecalledintheappropriateorderintheApplicationStartmethodNotethattheURLportionoftherouteissimplyamatchingmechanismfortherequestIftheURLmatchesaparticularroute,thenwespecifywhatcontrollershouldhandletherequestandwhatactionmethodshouldexecuteYoucancreateasmanyroutesasyoulike,butonerouteisprovidedforyouThisroutehasthetemplate,{controller}{action}{id}NOTEThisisaverygenericrouteandcouldbeusedformany,manydifferentwebrequestsTokensaredenotedbytheinclusionof{braces},andthewordenclosedinbracesmatcheswithavaluetheMVCFrameworkunderstandsThemostcommonthatwe'llbeinterestedinarecontrollerandactionThecontrollerroutevalueisaspecialvaluethattheSystemWebMvcMvcHandlerclassusestocallintotheIControllerFactoryinterfaceThisisalsotheroutewewillbeusingfortherestofthechapter,sowewillbecontentwithaURLintheformofhttp:MvcContriborgcontrollernameactionnameThebasicroutehandlerisaninstanceofIRouteHandlernamedMvcRouteHandlerWehavecompletecontrolandcouldprovideourownimplementationofIRouteHandlerifwewished,butwewillsavethatforalaterchapterBeforewespinupourfirstcontroller,letusexaminewhatisdifferentaboutthewebconfigfileinanMVCWebApplicationprojectThedifferencesareeasytospotJustlookfor“routing”or“MVC”OnedifferenceweseeisthatanewIHttpModuleisregisterdintheconfigfileHere,weseetheUrlRoutingModuleinlistingListingUniqueadditiontothewebconfigfileTherestofthewebconfigfileisstandardforNet<addname="UrlRoutingModule"type="SystemWebRoutingUrlRoutingModule,SystemWebRouting,Version=,Culture=neutral,PublicKeyToken=BFADE">TheUrlRoutingModuleevaluatesarequestandseesifitmatchesaroutethatisstoredintheRouteTableIftheroutematches,itoverridesthedefaulthandler(IHttpHandler)fortherequestsothattheMVCFrameworkhandlestherequestWearegoingtoexamineourfirstcontrollerasameanstohandlearoutefortheURLhomeInthenextsectionyouwillseehowallthepiecesofthestarterprojectfittogetherRunningwiththeStarterProjectThiswillbeaveryshortsectionWearegoingtomovethroughthestarterprojectveryquicklylookingateachpieceofprovidedcodeEachservesasanexampleofhowtofitcodetogetherwhenwritinganapplicationwiththepresentationlayerpoweredbytheASPNETMVCFrameworkBeforelookingatcode,runthewebapplicationbypressingCTRLF,andyoushouldseesomethinglikethatinfigureFigureThestarterprojectcomeswillabasiclayoutandcssNoticethatthestarterprojectincludessomenavigation,aLogOn,andsomecontentTheprovidedCSSprovidessomesimpleformattingontopofXHTMLNoticetheURLintheaddressbaris"home"alsowillbringupthesamepagesinceourroutespecifies"home"asthedefaultcontrollerThisURLdoesnothaveanextension,soifyouarerunningonIIS,youmusteitheraddawildcardmappingorinstallanISAPIfilterthatprovidesthisfunctionalityInstallationonIISiscoveredinmoredetailchapterSinceyouarealreadyfamiliarwiththeASPNETrequestpipeline,wewillbrieflymovethroughhowthisrequestmakesitswaytoanASPNETMVCcontrollerThefollowingoutlineshowtherequestmovesthroughASPNET,tothecontrollerandthroughtheview:RequestcomesintoHomeIISdeterminestherequestshouldbehandledbyASPNETASPNETgivesallHttpModulesachancetomodifytherequestTheUrlRoutingModuledeterminesthattheURLmatchesarouteconfiguredintheapplicationTheUrlRoutingModulegetstheappropriateIHttpHandlerfromtheIRouteHandlerthatisusedinthematchingroute(mostofthetime,MvcRouteHandler)asthehandlerfortherequestTheMvcRouteHandlerconstructsandreturnsMvcHandlerTheMvcHandler,whichimplementsIHttpHandlerexecutesProcessRequestTheMvcHandlerusesIControllerFactorytoobtainaninstanceofIControllerusingthe"controller"routedatafromtheroute{controller}{action}{id}TheHomeControllerisfound,anditsExecutemethodisinvokedTheHomeControllerinvokestheIndexactionTheIndexactionaddssomeobjectstotheViewDatadictionaryTheHomeControllerinvokestheActionResultreturnedfromtheaction,whichrendersaviewThe“index”viewintheviewsfolderdisplaystheobjectsinViewDataTheview,derivedfromSystemWebMvcViewPage,executesitsProcessRequestmethodASPNETrenderstheresponsetothebrowserTheaboveisthesimplifiedlifeofarequesthandledbytheASPNETMVCFrameworkIfyouarecuriousaboutmoredetails,youcanbrowsethesourcecode,whichisavailableathttp:wwwcodeplexcomaspnetTheabovestepsaresufficientforunderstandinghowtowritecodebasedontheASPNETMVCFramework,andm

用户评论(0)

0/200

精彩专题

上传我的资料

每篇奖励 +1积分

资料评分:

/45
仅支持在线阅读

意见
反馈

立即扫码关注

爱问共享资料微信公众号

返回
顶部

举报
资料