SlideShare una empresa de Scribd logo
1 de 50
ASP.NET MVC Best Practices Simone ChiarettaSolution Developer, Avanade http://codeclimber.net.nz Twitter: @simonech 21 Ottobre 2009
Thanks to the Sponsors
Who the hell am I? Simone Chiaretta Work for Avanade Italy Microsoft MVP ASP.NET Blogger – http://codeclimber.net.nz Founder of UGIALT.NET OpenSource developer Climber All Around Nice Guy
Agenda ASP.NET MVC Best Practices Would 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 case The Controller asks the Model for data The request hits the controller Model 2 1 3 Controller Browser The Model gives the data back to the Controller The controller formats the data and passes them to the View View 4 5 The view renders the HTML that needs to be sent to the client 5
Controller
Delete “AccountController” Best Practice n° 1
1 – Delete “AccountController” You will probably never use these account management pages Keeping demo code in a production application is EVIL Delete it 
Isolate controllers from the external World Best Practice n° 2
2 - Isolate controllers from the outside World HttpContext Data Access classes Configuration management Logging Clock Etc…
2 - Isolate controllers from the outside World Not testable application Not flexible application
Use a IoC Container Best Practice n° 3
What’s Dependency Injection 13
What’s Dependency Injection BAD
What’s Dependency Injection BETTER
What’s Dependency Injection BUT
Inversion of Control With IoC
IoC inside ASP.NET MVC Extend ControllerFactory Many ControllerFactory ready available StructureMap Spring Unity Windsor Ninject ...
IoC inside ASP.NET MVC using Ninject v2 Global.asax inherits from NinjectHttpApplication Helper to configure all controllers: RegisterAllControllersIn(“assemblyName”);
Don’t use “Magic strings” Best Practice n° 4
Say NO to Magic Strings Never use ViewData[“key”] Always create a ViewModel for each View View must inherit from System.Web.Mvc.ViewPage<ListViewModel>
Build your own “personal” conventions Best Practice n° 5
Build your own “personal” conventions ASP.NET MVC is the base on which to build your own reference architecture Controllers (and views) inherint from your own base class
Pay attention to Verbs Best Practice n° 6
Pay attention to Verbs What happens when you refresh (or go back) after you submit a form? 25
PRG Pattern View sends data in POST Controller validates Renders the View with errors (POST) Redirect in GET View renders the results in GET
Pay attention to Verbs Show data in GET Modify data in POST
Model
DomainModel != ViewModel Best Practice n° 7
DomainModel != ViewModel DomainModel Data + Behaviours hierarchical, complex types ViewModel Only Data Flat, only strings
DomainModel != ViewModel How to avoid getting bored writing tedious mapping code? AutoMapper Mapper.Map<Post, ShowPostModel>(post)
Use ActionFilter for “shared” data Best Practice n° 8
Components in ASP.NET MVC RenderPartial The Controller must “create” all data needed by all the partials RenderAction (futures) Smells (view calls a controller) More difficult to test Custom HtmlHelpers Ok for some HTML, but must not have logic
Action Filtes Defined as Attributi Allow you to execute “code” During the Autenthorization phase If an exception occurs Before an Action After an Action Before the rendering of a view After the rendering of a view “Core” filters Authorize OutputCache
Action Filter + Render Partial Controller: Has code for his “main concern” and “create” the main data View: Renders the main output Calls the various PartialViews Action Filters: Load data for the partial views Partial views Render data loaded via Action Filters
View
Do NOT use code-behind Best Practice n° 9
Do NOT use code-behind NEVER
Write HTML when you can Best Practice n° 10
Write HTML when you can You MUST learn HTML Do never use HtmlHelpers that ONLY abstract HTML awat <%= Html.Submit(“Salva”) %> vs <input type=“submit” value=“Salva” />
If there is an if, write an HtmlHelper Best Practice n° 11
If there is an if, write an HtmlHelper View must not have logic Allowed: if - foreach When possible, “hides” them in HtmlHelpers
Choose your View Engine carefully Best Practice n° 12
Choose your View Engine carefully The default is WebFormViewEngine Not the best available Choose the one that most suits you
Choose your View Engine carefully Spark View Engine The flow is managed by HTML It’s a templating engine Other Features Renders PDF Evaluates templates also with Javascript
Beginning ASP.NET MVC Simone Chiaretta & Keyvan Nayyeri TOC: MVC Testing And more... http://bit.ly/BeginningASPNETMVC
Contacts – Simone Chiaretta MSN: simone_ch@hotmail.com Blog: English: http://codeclimber.net.nz/ Italian: http://blogs.ugidotnet.org/piyo/ Twitter: @simonech 47
Credits These talk has been inspired by Sebastien Lambla (founder of Caffeine IT) and his ASP.NET MVC Best Practices Watch his talk (which is way better than mine): http://serialseb.blogspot.com/2009/05/my-mvc-best-practices-talk.html Read his blog: http://serialseb.blogspot.com/ 48
Q&A 49

Más contenido relacionado

Destacado

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 ncubeMalisa Ncube
 
Getting Started with ASP.NET MVC
Getting Started with ASP.NET MVCGetting Started with ASP.NET MVC
Getting Started with ASP.NET MVCshobokshi
 
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 oceanSimone 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 ExpressionsKurt Reinhardt
 
Web api scalability and performance
Web api scalability and performanceWeb api scalability and performance
Web api scalability and performanceHimanshu Desai
 
Crystal Reports: Basics
Crystal Reports: BasicsCrystal Reports: Basics
Crystal Reports: BasicsNet at Work
 
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 MikrajAminuddin 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 projectKaing 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 2010Slideshare
 

Destacado (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
 

Más de 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
 
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 4Simone Chiaretta
 
FeedTso, History of a WP7 FeedReader
FeedTso, History of a WP7 FeedReaderFeedTso, History of a WP7 FeedReader
FeedTso, History of a WP7 FeedReaderSimone 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 MVCSimone 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
 
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.comSimone Chiaretta
 

Más de 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
 

Último

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 

Último (20)

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 

ASP.NET MVC Best Practices

  • 1. ASP.NET MVC Best Practices Simone ChiarettaSolution Developer, Avanade http://codeclimber.net.nz Twitter: @simonech 21 Ottobre 2009
  • 2. Thanks to the Sponsors
  • 3. Who the hell am I? Simone Chiaretta Work for Avanade Italy Microsoft MVP ASP.NET Blogger – http://codeclimber.net.nz Founder of UGIALT.NET OpenSource developer Climber All Around Nice Guy
  • 4. Agenda ASP.NET MVC Best Practices Would 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 case The Controller asks the Model for data The request hits the controller Model 2 1 3 Controller Browser The Model gives the data back to the Controller The controller formats the data and passes them to the View View 4 5 The view renders the HTML that needs to be sent to the client 5
  • 9. 1 – Delete “AccountController” You will probably never use these account management pages Keeping demo code in a production application is EVIL Delete it 
  • 10. Isolate controllers from the external World Best Practice n° 2
  • 11. 2 - Isolate controllers from the outside World HttpContext Data Access classes Configuration management Logging Clock Etc…
  • 12. 2 - Isolate controllers from the outside World Not testable application Not flexible application
  • 13. Use a IoC Container Best Practice n° 3
  • 19. IoC inside ASP.NET MVC Extend ControllerFactory Many ControllerFactory ready available StructureMap Spring Unity Windsor Ninject ...
  • 20. IoC inside ASP.NET MVC using Ninject v2 Global.asax inherits from NinjectHttpApplication Helper to configure all controllers: RegisterAllControllersIn(“assemblyName”);
  • 21. Don’t use “Magic strings” Best Practice n° 4
  • 22. Say NO to Magic Strings Never use ViewData[“key”] Always create a ViewModel for each View View must inherit from System.Web.Mvc.ViewPage<ListViewModel>
  • 23. Build your own “personal” conventions Best Practice n° 5
  • 24. Build your own “personal” conventions ASP.NET MVC is the base on which to build your own reference architecture Controllers (and views) inherint from your own base class
  • 25. Pay attention to Verbs Best Practice n° 6
  • 26. Pay attention to Verbs What happens when you refresh (or go back) after you submit a form? 25
  • 27. PRG Pattern View sends data in POST Controller validates Renders the View with errors (POST) Redirect in GET View renders the results in GET
  • 28. Pay attention to Verbs Show data in GET Modify data in POST
  • 29. Model
  • 30. DomainModel != ViewModel Best Practice n° 7
  • 31. DomainModel != ViewModel DomainModel Data + Behaviours hierarchical, complex types ViewModel Only Data Flat, only strings
  • 32. DomainModel != ViewModel How to avoid getting bored writing tedious mapping code? AutoMapper Mapper.Map<Post, ShowPostModel>(post)
  • 33. Use ActionFilter for “shared” data Best Practice n° 8
  • 34. Components in ASP.NET MVC RenderPartial The Controller must “create” all data needed by all the partials RenderAction (futures) Smells (view calls a controller) More difficult to test Custom HtmlHelpers Ok for some HTML, but must not have logic
  • 35. Action Filtes Defined as Attributi Allow you to execute “code” During the Autenthorization phase If an exception occurs Before an Action After an Action Before the rendering of a view After the rendering of a view “Core” filters Authorize OutputCache
  • 36. Action Filter + Render Partial Controller: Has code for his “main concern” and “create” the main data View: Renders the main output Calls the various PartialViews Action Filters: Load data for the partial views Partial views Render data loaded via Action Filters
  • 37. View
  • 38. Do NOT use code-behind Best Practice n° 9
  • 39. Do NOT use code-behind NEVER
  • 40. Write HTML when you can Best Practice n° 10
  • 41. Write HTML when you can You MUST learn HTML Do 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 HtmlHelper Best Practice n° 11
  • 43. If there is an if, write an HtmlHelper View must not have logic Allowed: if - foreach When possible, “hides” them in HtmlHelpers
  • 44. Choose your View Engine carefully Best Practice n° 12
  • 45. Choose your View Engine carefully The default is WebFormViewEngine Not the best available Choose the one that most suits you
  • 46. Choose your View Engine carefully Spark View Engine The flow is managed by HTML It’s a templating engine Other Features Renders PDF Evaluates templates also with Javascript
  • 47. Beginning ASP.NET MVC Simone Chiaretta & Keyvan Nayyeri TOC: MVC Testing And more... http://bit.ly/BeginningASPNETMVC
  • 48. Contacts – Simone Chiaretta MSN: simone_ch@hotmail.com Blog: English: http://codeclimber.net.nz/ Italian: http://blogs.ugidotnet.org/piyo/ Twitter: @simonech 47
  • 49. Credits These talk has been inspired by Sebastien Lambla (founder of Caffeine IT) and his ASP.NET MVC Best Practices Watch his talk (which is way better than mine): http://serialseb.blogspot.com/2009/05/my-mvc-best-practices-talk.html Read his blog: http://serialseb.blogspot.com/ 48