SlideShare a Scribd company logo
ASP.NET MVC Best PracticesSimone ChiarettaSolution Developer, Avanadehttp://codeclimber.net.nzTwitter: @simonech21 Ottobre 2009
Thanks to the Sponsors
Who the hell am I?Simone ChiarettaWork for Avanade ItalyMicrosoft MVP ASP.NETBlogger – http://codeclimber.net.nzFounder of UGIALT.NETOpenSource developerClimberAll Around Nice Guy
AgendaASP.NET MVC Best PracticesWould you like someone to tell you the final a movie before you watch it?3
What ASP.NET MVC is?It’s an advanced session... You should already know 
Just in caseThe Controller asks the Model for dataThe request hits the controllerModel213ControllerBrowserThe Model gives the data back to the ControllerThe controller formats the data and passes them to the ViewView45The view renders the HTML that needs to be sent to the client5
Controller
Delete “AccountController”Best Practice n° 1
1 – Delete “AccountController”You will probably never use these account management pagesKeeping demo code in a production application is EVILDelete it 
Isolate controllers from the external WorldBest Practice n° 2
2 - Isolate controllers from the outside WorldHttpContextData Access classesConfiguration managementLoggingClockEtc…
2 - Isolate controllers from the outside WorldNot testable applicationNot flexible application
Use a IoC ContainerBest Practice n° 3
What’s Dependency Injection13
What’s Dependency InjectionBAD
What’s Dependency InjectionBETTER
What’s Dependency InjectionBUT
Inversion of ControlWith IoC
IoC inside ASP.NET MVCExtend ControllerFactoryMany ControllerFactory ready availableStructureMapSpringUnityWindsorNinject...
IoC inside ASP.NET MVC using Ninject v2Global.asax inherits from NinjectHttpApplicationHelper to configure all controllers:RegisterAllControllersIn(“assemblyName”);
Don’t use “Magic strings”Best Practice n° 4
Say NO to Magic StringsNever use ViewData[“key”]Always create a ViewModel for each ViewView must inherit fromSystem.Web.Mvc.ViewPage<ListViewModel>
Build your own “personal” conventionsBest Practice n° 5
Build your own “personal” conventionsASP.NET MVC is the base on which to build your own reference architectureControllers (and views) inherint from your own base class
Pay attention to VerbsBest Practice n° 6
Pay attention to VerbsWhat happens when you refresh (or go back) after you submit a form?25
PRG PatternView sends data in POSTController validatesRenders the View with errors (POST)Redirect in GETView renders the results in GET
Pay attention to VerbsShow data in GETModify data in POST
Model
DomainModel != ViewModelBest Practice n° 7
DomainModel != ViewModelDomainModelData + Behaviourshierarchical, complex typesViewModelOnly DataFlat, only strings
DomainModel != ViewModelHow to avoid getting bored writing tedious mapping code?AutoMapperMapper.Map<Post, ShowPostModel>(post)
Use ActionFilter for “shared” dataBest Practice n° 8
Components in ASP.NET MVCRenderPartialThe Controller must “create” all data needed by all the partialsRenderAction (futures)Smells (view calls a controller)More difficult to testCustom HtmlHelpersOk for some HTML, but must not have logic
Action FiltesDefined as AttributiAllow you to execute “code”During the Autenthorization phaseIf an exception occursBefore an ActionAfter an ActionBefore the rendering of a viewAfter the rendering of a view“Core” filtersAuthorizeOutputCache
Action Filter + Render PartialController:Has code for his “main concern” and “create” the main dataView:Renders the main outputCalls the various PartialViewsAction Filters:Load data for the partial viewsPartial viewsRender data loaded via Action Filters
View
Do NOT use code-behindBest Practice n° 9
Do NOT use code-behindNEVER
Write HTML when you canBest Practice n° 10
Write HTML when you canYou MUST learn HTMLDo never use HtmlHelpers that ONLY abstract HTML awat<%= Html.Submit(“Salva”) %>vs<input type=“submit” value=“Salva” />
If there is an if, write an HtmlHelperBest Practice n° 11
If there is an if, write an HtmlHelperView must not have logicAllowed: if - foreachWhen possible, “hides” them in HtmlHelpers
Choose your View Engine carefullyBest Practice n° 12
Choose your View Engine carefullyThe default is WebFormViewEngineNot the best availableChoose the one that most suits you
Choose your View Engine carefullySpark View EngineThe flow is managed by HTMLIt’s a templating engineOther FeaturesRenders PDFEvaluates templates also with Javascript
Beginning ASP.NET MVCSimone Chiaretta & Keyvan NayyeriTOC:MVCTestingAnd more...http://bit.ly/BeginningASPNETMVC
Contacts – Simone ChiarettaMSN: simone_ch@hotmail.comBlog:English: http://codeclimber.net.nz/Italian: http://blogs.ugidotnet.org/piyo/Twitter: @simonech47
CreditsThese talk has been inspired by Sebastien Lambla (founder of Caffeine IT) and his ASP.NET MVC Best PracticesWatch his talk (which is way better than mine): http://serialseb.blogspot.com/2009/05/my-mvc-best-practices-talk.htmlRead his blog: http://serialseb.blogspot.com/48
Q&A49

More Related Content

Viewers also liked

ASP.NET MVC Best Practices malisa ncube
ASP.NET MVC Best Practices   malisa ncubeASP.NET MVC Best Practices   malisa ncube
ASP.NET MVC Best Practices malisa ncube
Malisa Ncube
 
Getting Started with ASP.NET MVC
Getting Started with ASP.NET MVCGetting Started with ASP.NET MVC
Getting Started with ASP.NET MVC
shobokshi
 
05 gui 07
05 gui 0705 gui 07
05 gui 07
Niit Care
 
Crystal repor
Crystal reporCrystal repor
Crystal repor
nghia_790a
 
OpenROV: Node.js takes a dive into the ocean
OpenROV: Node.js takes a dive into the oceanOpenROV: Node.js takes a dive into the ocean
OpenROV: Node.js takes a dive into the ocean
Simone Chiaretta
 
Crystal Reports - The Power and Possibilities of SQL Expressions
Crystal Reports - The Power and Possibilities of SQL ExpressionsCrystal Reports - The Power and Possibilities of SQL Expressions
Crystal Reports - The Power and Possibilities of SQL Expressions
Kurt Reinhardt
 
Web api scalability and performance
Web api scalability and performanceWeb api scalability and performance
Web api scalability and performance
Himanshu Desai
 
Crystal Reports: Basics
Crystal Reports: BasicsCrystal Reports: Basics
Crystal Reports: Basics
Net at Work
 
MSDN - ASP.NET MVC
MSDN - ASP.NET MVCMSDN - ASP.NET MVC
MSDN - ASP.NET MVC
Maarten Balliauw
 
Nota Pendidikan Islam Tahun 5 Israk dan Mikraj
Nota Pendidikan Islam Tahun 5 Israk dan MikrajNota Pendidikan Islam Tahun 5 Israk dan Mikraj
Nota Pendidikan Islam Tahun 5 Israk dan Mikraj
Aminuddin Mohamad
 
Generate a report using crystal reports in visual studio 2010 code project
Generate a report using crystal reports in visual studio 2010   code projectGenerate a report using crystal reports in visual studio 2010   code project
Generate a report using crystal reports in visual studio 2010 code project
Kaing Menglieng
 
Crystal report generation in visual studio 2010
Crystal report generation in visual studio 2010Crystal report generation in visual studio 2010
Crystal report generation in visual studio 2010
Slideshare
 
Crystal report
Crystal reportCrystal report

Viewers also liked (15)

ASP.NET MVC Best Practices malisa ncube
ASP.NET MVC Best Practices   malisa ncubeASP.NET MVC Best Practices   malisa ncube
ASP.NET MVC Best Practices malisa ncube
 
Getting Started with ASP.NET MVC
Getting Started with ASP.NET MVCGetting Started with ASP.NET MVC
Getting Started with ASP.NET MVC
 
05 gui 07
05 gui 0705 gui 07
05 gui 07
 
Slide isra-dan-mikraj
Slide isra-dan-mikrajSlide isra-dan-mikraj
Slide isra-dan-mikraj
 
Crystal repor
Crystal reporCrystal repor
Crystal repor
 
OpenROV: Node.js takes a dive into the ocean
OpenROV: Node.js takes a dive into the oceanOpenROV: Node.js takes a dive into the ocean
OpenROV: Node.js takes a dive into the ocean
 
Crystal Reports - The Power and Possibilities of SQL Expressions
Crystal Reports - The Power and Possibilities of SQL ExpressionsCrystal Reports - The Power and Possibilities of SQL Expressions
Crystal Reports - The Power and Possibilities of SQL Expressions
 
Web api scalability and performance
Web api scalability and performanceWeb api scalability and performance
Web api scalability and performance
 
Crystal Reports: Basics
Crystal Reports: BasicsCrystal Reports: Basics
Crystal Reports: Basics
 
Asp.Net MVC 5
Asp.Net MVC 5Asp.Net MVC 5
Asp.Net MVC 5
 
MSDN - ASP.NET MVC
MSDN - ASP.NET MVCMSDN - ASP.NET MVC
MSDN - ASP.NET MVC
 
Nota Pendidikan Islam Tahun 5 Israk dan Mikraj
Nota Pendidikan Islam Tahun 5 Israk dan MikrajNota Pendidikan Islam Tahun 5 Israk dan Mikraj
Nota Pendidikan Islam Tahun 5 Israk dan Mikraj
 
Generate a report using crystal reports in visual studio 2010 code project
Generate a report using crystal reports in visual studio 2010   code projectGenerate a report using crystal reports in visual studio 2010   code project
Generate a report using crystal reports in visual studio 2010 code project
 
Crystal report generation in visual studio 2010
Crystal report generation in visual studio 2010Crystal report generation in visual studio 2010
Crystal report generation in visual studio 2010
 
Crystal report
Crystal reportCrystal report
Crystal report
 

More from Simone Chiaretta

Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...
Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...
Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...
Simone Chiaretta
 
La UX delle cose
La UX delle coseLa UX delle cose
La UX delle cose
Simone Chiaretta
 
UGIALT.net Keynote
UGIALT.net KeynoteUGIALT.net Keynote
UGIALT.net Keynote
Simone Chiaretta
 
What's new in asp.net mvc 4
What's new in asp.net mvc 4What's new in asp.net mvc 4
What's new in asp.net mvc 4
Simone Chiaretta
 
FeedTso, History of a WP7 FeedReader
FeedTso, History of a WP7 FeedReaderFeedTso, History of a WP7 FeedReader
FeedTso, History of a WP7 FeedReader
Simone Chiaretta
 
Ruby on Rails vs ASP.NET MVC
Ruby on Rails vs ASP.NET MVCRuby on Rails vs ASP.NET MVC
Ruby on Rails vs ASP.NET MVC
Simone Chiaretta
 
Design for testability as a way to good coding (SOLID and IoC)
Design for testability as a way to good coding (SOLID and IoC)Design for testability as a way to good coding (SOLID and IoC)
Design for testability as a way to good coding (SOLID and IoC)
Simone Chiaretta
 
The ViewModel pattern
The ViewModel patternThe ViewModel pattern
The ViewModel pattern
Simone Chiaretta
 
ASP.NET MVC Extensibility
ASP.NET MVC ExtensibilityASP.NET MVC Extensibility
ASP.NET MVC Extensibility
Simone Chiaretta
 
Lavorare con applicazioni Brownfield: il caso di 39x27.com
Lavorare con applicazioni Brownfield: il caso di 39x27.comLavorare con applicazioni Brownfield: il caso di 39x27.com
Lavorare con applicazioni Brownfield: il caso di 39x27.com
Simone Chiaretta
 

More from Simone Chiaretta (10)

Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...
Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...
Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...
 
La UX delle cose
La UX delle coseLa UX delle cose
La UX delle cose
 
UGIALT.net Keynote
UGIALT.net KeynoteUGIALT.net Keynote
UGIALT.net Keynote
 
What's new in asp.net mvc 4
What's new in asp.net mvc 4What's new in asp.net mvc 4
What's new in asp.net mvc 4
 
FeedTso, History of a WP7 FeedReader
FeedTso, History of a WP7 FeedReaderFeedTso, History of a WP7 FeedReader
FeedTso, History of a WP7 FeedReader
 
Ruby on Rails vs ASP.NET MVC
Ruby on Rails vs ASP.NET MVCRuby on Rails vs ASP.NET MVC
Ruby on Rails vs ASP.NET MVC
 
Design for testability as a way to good coding (SOLID and IoC)
Design for testability as a way to good coding (SOLID and IoC)Design for testability as a way to good coding (SOLID and IoC)
Design for testability as a way to good coding (SOLID and IoC)
 
The ViewModel pattern
The ViewModel patternThe ViewModel pattern
The ViewModel pattern
 
ASP.NET MVC Extensibility
ASP.NET MVC ExtensibilityASP.NET MVC Extensibility
ASP.NET MVC Extensibility
 
Lavorare con applicazioni Brownfield: il caso di 39x27.com
Lavorare con applicazioni Brownfield: il caso di 39x27.comLavorare con applicazioni Brownfield: il caso di 39x27.com
Lavorare con applicazioni Brownfield: il caso di 39x27.com
 

Recently uploaded

IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Networks
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
Eric D. Schabell
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
rajancomputerfbd
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
Yevgen Sysoyev
 
Data Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining DataData Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining Data
Safe Software
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
SynapseIndia
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
Adam Dunkels
 
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdfARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
Inglês no Mundo Digital
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
Kief Morris
 
Amul milk launches in US: Key details of its new products ...
Amul milk launches in US: Key details of its new products ...Amul milk launches in US: Key details of its new products ...
Amul milk launches in US: Key details of its new products ...
chetankumar9855
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
bhumivarma35300
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
ishalveerrandhawa1
 
Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024
aakash malhotra
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
“Deploying Large Language Models on a Raspberry Pi,” a Presentation from Usef...
“Deploying Large Language Models on a Raspberry Pi,” a Presentation from Usef...“Deploying Large Language Models on a Raspberry Pi,” a Presentation from Usef...
“Deploying Large Language Models on a Raspberry Pi,” a Presentation from Usef...
Edge AI and Vision Alliance
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
BrainSell Technologies
 
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdfWhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
ArgaBisma
 
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
Priyanka Aash
 
The Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF GuideThe Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF Guide
Shiv Technolabs
 

Recently uploaded (20)

IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
 
Data Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining DataData Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining Data
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
 
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdfARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
 
Amul milk launches in US: Key details of its new products ...
Amul milk launches in US: Key details of its new products ...Amul milk launches in US: Key details of its new products ...
Amul milk launches in US: Key details of its new products ...
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
 
Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
“Deploying Large Language Models on a Raspberry Pi,” a Presentation from Usef...
“Deploying Large Language Models on a Raspberry Pi,” a Presentation from Usef...“Deploying Large Language Models on a Raspberry Pi,” a Presentation from Usef...
“Deploying Large Language Models on a Raspberry Pi,” a Presentation from Usef...
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
 
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdfWhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
 
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
 
The Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF GuideThe Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF Guide
 

ASP.NET MVC Best Practices

  • 1. ASP.NET MVC Best PracticesSimone ChiarettaSolution Developer, Avanadehttp://codeclimber.net.nzTwitter: @simonech21 Ottobre 2009
  • 2. Thanks to the Sponsors
  • 3. Who the hell am I?Simone ChiarettaWork for Avanade ItalyMicrosoft MVP ASP.NETBlogger – http://codeclimber.net.nzFounder of UGIALT.NETOpenSource developerClimberAll Around Nice Guy
  • 4. AgendaASP.NET MVC Best PracticesWould you like someone to tell you the final a movie before you watch it?3
  • 5. What ASP.NET MVC is?It’s an advanced session... You should already know 
  • 6. Just in caseThe Controller asks the Model for dataThe request hits the controllerModel213ControllerBrowserThe Model gives the data back to the ControllerThe controller formats the data and passes them to the ViewView45The view renders the HTML that needs to be sent to the client5
  • 9. 1 – Delete “AccountController”You will probably never use these account management pagesKeeping demo code in a production application is EVILDelete it 
  • 10. Isolate controllers from the external WorldBest Practice n° 2
  • 11. 2 - Isolate controllers from the outside WorldHttpContextData Access classesConfiguration managementLoggingClockEtc…
  • 12. 2 - Isolate controllers from the outside WorldNot testable applicationNot flexible application
  • 13. Use a IoC ContainerBest Practice n° 3
  • 19. IoC inside ASP.NET MVCExtend ControllerFactoryMany ControllerFactory ready availableStructureMapSpringUnityWindsorNinject...
  • 20. IoC inside ASP.NET MVC using Ninject v2Global.asax inherits from NinjectHttpApplicationHelper to configure all controllers:RegisterAllControllersIn(“assemblyName”);
  • 21. Don’t use “Magic strings”Best Practice n° 4
  • 22. Say NO to Magic StringsNever use ViewData[“key”]Always create a ViewModel for each ViewView must inherit fromSystem.Web.Mvc.ViewPage<ListViewModel>
  • 23. Build your own “personal” conventionsBest Practice n° 5
  • 24. Build your own “personal” conventionsASP.NET MVC is the base on which to build your own reference architectureControllers (and views) inherint from your own base class
  • 25. Pay attention to VerbsBest Practice n° 6
  • 26. Pay attention to VerbsWhat happens when you refresh (or go back) after you submit a form?25
  • 27. PRG PatternView sends data in POSTController validatesRenders the View with errors (POST)Redirect in GETView renders the results in GET
  • 28. Pay attention to VerbsShow data in GETModify data in POST
  • 29. Model
  • 31. DomainModel != ViewModelDomainModelData + Behaviourshierarchical, complex typesViewModelOnly DataFlat, only strings
  • 32. DomainModel != ViewModelHow to avoid getting bored writing tedious mapping code?AutoMapperMapper.Map<Post, ShowPostModel>(post)
  • 33. Use ActionFilter for “shared” dataBest Practice n° 8
  • 34. Components in ASP.NET MVCRenderPartialThe Controller must “create” all data needed by all the partialsRenderAction (futures)Smells (view calls a controller)More difficult to testCustom HtmlHelpersOk for some HTML, but must not have logic
  • 35. Action FiltesDefined as AttributiAllow you to execute “code”During the Autenthorization phaseIf an exception occursBefore an ActionAfter an ActionBefore the rendering of a viewAfter the rendering of a view“Core” filtersAuthorizeOutputCache
  • 36. Action Filter + Render PartialController:Has code for his “main concern” and “create” the main dataView:Renders the main outputCalls the various PartialViewsAction Filters:Load data for the partial viewsPartial viewsRender data loaded via Action Filters
  • 37. View
  • 38. Do NOT use code-behindBest Practice n° 9
  • 39. Do NOT use code-behindNEVER
  • 40. Write HTML when you canBest Practice n° 10
  • 41. Write HTML when you canYou MUST learn HTMLDo never use HtmlHelpers that ONLY abstract HTML awat<%= Html.Submit(“Salva”) %>vs<input type=“submit” value=“Salva” />
  • 42. If there is an if, write an HtmlHelperBest Practice n° 11
  • 43. If there is an if, write an HtmlHelperView must not have logicAllowed: if - foreachWhen possible, “hides” them in HtmlHelpers
  • 44. Choose your View Engine carefullyBest Practice n° 12
  • 45. Choose your View Engine carefullyThe default is WebFormViewEngineNot the best availableChoose the one that most suits you
  • 46. Choose your View Engine carefullySpark View EngineThe flow is managed by HTMLIt’s a templating engineOther FeaturesRenders PDFEvaluates templates also with Javascript
  • 47. Beginning ASP.NET MVCSimone Chiaretta & Keyvan NayyeriTOC:MVCTestingAnd more...http://bit.ly/BeginningASPNETMVC
  • 48. Contacts – Simone ChiarettaMSN: simone_ch@hotmail.comBlog:English: http://codeclimber.net.nz/Italian: http://blogs.ugidotnet.org/piyo/Twitter: @simonech47
  • 49. CreditsThese talk has been inspired by Sebastien Lambla (founder of Caffeine IT) and his ASP.NET MVC Best PracticesWatch his talk (which is way better than mine): http://serialseb.blogspot.com/2009/05/my-mvc-best-practices-talk.htmlRead his blog: http://serialseb.blogspot.com/48
  • 50. Q&A49