SlideShare a Scribd company logo
Umbraco MVC
A journey of discovery

Lotte Pitcher
Session Contents
Included:

Not Included:

• Introduction

• Best Practises for
Umbraco MVC

– MVC and Web Forms

• Umbraco MVC
– Walkthrough a sample site

• Pure MVC techniques
– Plugging into sample site

– J&J are doing a session
later

• Code First
– Or any other solution for
strongly typed models for
your content
MVC
• Model-View-Controller
Generated designer file

• Obligatory Diagram

Page.aspx
Page.aspx.cs

• Learning recommendation
– Pluralsight course
– MS free 6 hour video online
http://www.microsoftvirtualacademy.com/training-courses/
developing-asp-net-mvc-4-web-applications-jump-start
Common Features
• Alternative to Web Forms, not a replacement
• ASP.Net framework features available to both:
–
–
–
–
–

Authentication (forms/windows)
Membership and Roles
Caching
Session and Profile management
Configuration system
Some Key Benefits of MVC
• Full control over HTML
– No more <asp:Panel runat=“server”></asp:Panel>
– Easier to integrate JavaScript frameworks

• No viewstate
– Smaller page sizes

• Testable
– Anthony Dang‟s session
MVC v Web Forms Summary
• Learning curve with MVC
• With Umbraco MVC this is small
• Quote from Shannon at CG13
– Only reason not to do MVC is if you don‟t have the resources for
your team to learn it
Umbraco MVC Demo
• Simple site
– Home Page
– About Page
– Contact Us Page

• Umbraco back office
– Should all look pretty familiar
How was this set up?
• Visual Studio
– File > New Project > ASP.Net MVC 4 Web Application (Empty)

• Add Umbraco via Nuget
– Package manager console
PM> Install-Package UmbracoCms

• Install Umbraco
– As usual by loading in browser and following on-screen
instructions

• Initial Configuration
– Set up doc types
– Bring in assets (css, scripts etc)
Adding Templates
• Set default render engine to MVC
– ~/config/umbracoSettings.config
<defaultRenderingEngine>Mvc</defaultRenderingEngine>

• View overrides a master page of same name
– ~/masterpages/_Layout.master would be superceded by
~/views/_Layout.cshtml

• Good way to get going – „convert‟ existing master page

• Cheatsheet to help you
– http://our.umbraco.org/documentation/cheatsheets/Masterpages
2Views.pdf
Demo Site Templates
• Review the templates (views) in the demo site
– ~/Views/_Layout.cshtml
– ~/Views/HomePage.cshtml
– ~/Views/Partials/PrimaryNavigation.cshtml

• Our Umbraco has useful documentation
– our.umbraco.org/documentation/reference/templating/Mvc
– Plus on all other aspects of Umbraco MVC
View Locations
• Several places – discover by calling a missing view
Contact Form using a Surface Controller
• ~/Models/ContactFormModel.cs
– The model that defines the data that we want to collect

• ~/Controllers/ContactFormController.cs
– Must inherit from Umbraco.Web.MVC.SurfaceController
– public ActionResult RenderForm()

• Child Action method for displaying view
– public ActionResult HandleForm(ContactFormModel model)

• Method to handle posted data

• ~/Views/ContactForm/RenderForm.cshtml
– Html.BeginUmbracoForm<ContactFormController>(“HandleForm”)

• ~/Views/ContactPage.cshtml
– Html.Action(“RenderForm”, “ContactForm”)
Route Hijacking
• By default all of the front end routing is executed via the
Umbraco.Web.Mvc.RenderMvcController Index action
• “Hijacking” allows more control over how pages are rendered
• Controller should have the name of DocTypeAliasController
and inherit from Umbraco.Web.Mvc.RenderMvcController
– E.g. ~/Controllers/StatsPageController.cs

• Override the Index action

• See documentation on Our for more examples and options
– E.g. how to call methods dependent on the template being used
MVC Features
• Data Annotations
• Unobtrusive Validation
• Display Modes
• Display and Editor Templates
• Custom Attributes
• ViewBag
• Scaffolding
• Bundling and Minification
• Areas
Data Annotations
• Model/ContactFormModel.cs
–
–
–
–

Display name for SignUp [Display(Name = "Newsletter?")]
Name is required (with default error message) [Required]
Email is required (with bespoke error message)
Email must be valid (regular expression) [RegularExpression]

• View in browser
– SignUp now says „Newletter?‟
– Can‟t submit an empty form
– Can‟t submit an invalid email address

• Notes
– Custom annotations can defined
– Foolproof is example of nuget package you can add for more
advanced validation – e.g. RequiredIf
Unobtrusive Validation
• Currently validation done after post
• For unobtrusive (client-side) install 2 Nuget packages:
– jQuery
– Microsoft.jQuery.Unobstrusive.Validation

• Allow in web.config
– <add key="ClientValidationEnabled" value="true" />
– <add key="UnobtrusiveJavaScriptEnabled" value="true" />

• Reference scripts in ContactPage.cshtml (or in master
layout if used a lot)
• ContactUs.css has css for styling error messages and
invalid controls
Display Modes
• MVC has a default display mode already called „Mobile‟
–
–
–
–

iPhone is viewed as Mobile, iPad isn‟t
Copy _Layout.cshtml and rename _Layout.Mobile.cshtml
Make a difference to the mobile layout
View site using browser that is simulating a mobile

• Allow switching between modes
– Enable Controllers/ViewSwitcherController.cs
– Views/Shared/ViewSwitcher.cshtml
• ViewContext.HttpContext.GetOverriddenBrowser().IsMobileDevice

– Add html helper to footer in both layouts

• Notes
– If „Mobile‟ version does not exist then just uses standard
– Can specify own display modes and rules as required
Display and Editor Templates
• Views/ContactForm/RenderForm.cshtml
– Has examples of both @Html.EditorFor and
@Html.DisplayFor

• Want to replace all tick boxes for bools with dropdown
–
–
–
–

Views/EditorTemplates/Boolean.cshtml
Views/DisplayTemplates/Boolean.cshtml
Should now be dropdown and text for display not box
Display modes also work – Boolean.Mobile.cshtml

• Notes
– Have a template that matches the name of the „type‟ of the
property for all properties,
– Or annotate specific properties with
[UIHint(“TemplateName”)]
HTML5 and Custom Attributes
• E.g: you want to have styling control over Email field
• Option 1 – HTML 5 attribute
– [DataType(DataType.EmailAddress)] annotation causes
MVC to output input type=“email” not type=“text”

– Can then style against input[type=email]

• Option 2 – Specify CSS
– Remove DataType annotation
– Views/ContactForm/RenderForm.cshtml
– Change @Html.EditorFor(x => Model.Email) to
@Html.TextBoxFor(x => Model.Email, new { @class =
"email"})
ViewBag
• ViewBag is a dynamic object
– Can add properties to it in the controller
• ViewBag.PageVisits = 123;

– Views can read and update the ViewBag
– NB partial views only get passed a copy of the ViewBag, so they
can access it, but not update it

• Controller
– This is the “recommended” way to pass the data needed to
populate a dropdown list if needs to be got from database

• View
– “Standard” way for a view to set the page title that is then
rendered by layout
Scaffolding
• A technique to quickly generate a basic outline of your
software that you can then edit and customise
• NuGet package: UmbracoCms.Scaffolding
– Compilation error after installing? Shut VS and re-open
– This will create a model, surface controller and view

• For example
– PM> Scaffold SurfaceController ContactForm2
Name, Email, Signup

– Generates 3 files with a place to start from:
• ~/Models/ContactForm2Model.cs
• ~/Controllers/SurfaceControllers/ContactForm2SurfaceController.cs
• ~/Views/ContactForm2Surfce/ContactForm2.cshtml

• Customise templates in ~/CodeTemplates
Bundling and Minification
• Combine and minify script files and stylesheets to
improve request load time
• Debug mode true?
– Renders individual source versions so editing easier

• Debug mode false?
– Should render bundled/minified
– If change made to a bundled file, the bundle link gets recreated

• Blog from The Outfield
– http://www.theoutfield.net/blog/2013/09/mvc-unobtrusivevalidation-in-umbraco

• Optimus package for doing this via the back office
– http://our.umbraco.org/projects/developer-tools/optimus
Areas
• An Area is “partition” of an MVC site
– Own folders for Models, Views and Controllers
– With some „tweaks‟ can use the same Layouts as Umbraco
pages

• Why?
– If you have existing MVC functionality you want to bring into an
Umbraco MVC site,
– or you want to develop an section of the site that does not need
any content management

• Example
– Members only area that we want to develop as quickly as
possible – client has no requirement for editing pages

• Will be a blog post!
Summary
• Have a go - start with converting an existing master page
to a view
• Lots of MVC features that can plugged in when you are
ready
• Go to “J&J‟s” session on their hybrid MVC framework
session for their thoughts on best practises
• Resources (follow @lottepitcher):
– This presentation on SlideShare
– The finished Visual Studio solution is available here:
https://www.dropbox.com/s/le5t9wqldg2zx2u/UKFestivalMVC.zip

More Related Content

What's hot (19)

PPTX
Asp.net MVC training session
Hrichi Mohamed
 
PPT
Architecting RIAs with Silverlight
Josh Holmes
 
PPTX
Introduction to HTML5 and CSS3
Chandra S Oemarjadi
 
PDF
The road to professional web development
Christian Heilmann
 
PPTX
ASP.NET MVC Performance
rudib
 
PPTX
ASP.NET MVC for Begineers
Shravan Kumar Kasagoni
 
PPTX
Modern Applications With Asp.net Core 5 and Vue JS 3
Alexandre Malavasi
 
PPT
CTTDNUG ASP.NET MVC
Barry Gervin
 
PDF
Webforms or MVC
Aslam Siddiqui
 
PPTX
3-TIER ARCHITECTURE IN ASP.NET MVC
Mohd Manzoor Ahmed
 
PPT
Advanced Web Development
Robert J. Stein
 
PPTX
ASP .NET MVC
eldorina
 
PDF
A 20 minute introduction to AngularJS for XPage developers
Mark Leusink
 
PPTX
Single Page Applications on JavaScript and ASP.NET MVC4
Yuriy Shapovalov
 
PPTX
Web matrix part 2
yuvaraj72
 
PDF
ASP.NET MVC 3
Buu Nguyen
 
PDF
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha
 
PPTX
Asp.net mvc presentation by Nitin Sawant
Nitin S
 
PPTX
Angular on ASP.NET MVC 6
Noam Kfir
 
Asp.net MVC training session
Hrichi Mohamed
 
Architecting RIAs with Silverlight
Josh Holmes
 
Introduction to HTML5 and CSS3
Chandra S Oemarjadi
 
The road to professional web development
Christian Heilmann
 
ASP.NET MVC Performance
rudib
 
ASP.NET MVC for Begineers
Shravan Kumar Kasagoni
 
Modern Applications With Asp.net Core 5 and Vue JS 3
Alexandre Malavasi
 
CTTDNUG ASP.NET MVC
Barry Gervin
 
Webforms or MVC
Aslam Siddiqui
 
3-TIER ARCHITECTURE IN ASP.NET MVC
Mohd Manzoor Ahmed
 
Advanced Web Development
Robert J. Stein
 
ASP .NET MVC
eldorina
 
A 20 minute introduction to AngularJS for XPage developers
Mark Leusink
 
Single Page Applications on JavaScript and ASP.NET MVC4
Yuriy Shapovalov
 
Web matrix part 2
yuvaraj72
 
ASP.NET MVC 3
Buu Nguyen
 
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha
 
Asp.net mvc presentation by Nitin Sawant
Nitin S
 
Angular on ASP.NET MVC 6
Noam Kfir
 

Similar to "Umbraco MVC - a journey of discovery" - Lotte Pitcher (20)

PPTX
Getting started with MVC 5 and Visual Studio 2013
Thomas Robbins
 
PPTX
MVC Framework
Ashton Feller
 
PPTX
MVC & SQL_In_1_Hour
Dilip Patel
 
PPTX
MV* presentation frameworks in Javascript: en garde, pret, allez!
Roberto Messora
 
PPTX
Mvc
Furqan Ashraf
 
PDF
Web components - An Introduction
cherukumilli2
 
PDF
Staging Drupal 8 31 09 1 3
Drupalcon Paris
 
PPTX
Office 365 Saturday (Sydney) - SharePoint framework – build integrated user e...
Anupam Ranku
 
PPTX
Sitecore mvc
pratik satikunvar
 
PDF
Asp 1-mvc introduction
Fajar Baskoro
 
PPTX
Introduction to Visual studio 2012
Prashant Chaudhary
 
PDF
CFWheels - Pragmatic, Beautiful Code
indiver
 
PPTX
ASP.NET MVC 5 - EF 6 - VS2015
Hossein Zahed
 
PPTX
2011 NetUG HH: ASP.NET MVC & HTML 5
Daniel Fisher
 
PPTX
Training: MVVM Pattern
Betclic Everest Group Tech Team
 
PPTX
Vue micro frontend implementation patterns
Albert Brand
 
PDF
Introduction to Angular Js
Professional Guru
 
PPT
Mvc 130330091359-phpapp01
Jennie Gajjar
 
PDF
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Getting started with MVC 5 and Visual Studio 2013
Thomas Robbins
 
MVC Framework
Ashton Feller
 
MVC & SQL_In_1_Hour
Dilip Patel
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
Roberto Messora
 
Web components - An Introduction
cherukumilli2
 
Staging Drupal 8 31 09 1 3
Drupalcon Paris
 
Office 365 Saturday (Sydney) - SharePoint framework – build integrated user e...
Anupam Ranku
 
Sitecore mvc
pratik satikunvar
 
Asp 1-mvc introduction
Fajar Baskoro
 
Introduction to Visual studio 2012
Prashant Chaudhary
 
CFWheels - Pragmatic, Beautiful Code
indiver
 
ASP.NET MVC 5 - EF 6 - VS2015
Hossein Zahed
 
2011 NetUG HH: ASP.NET MVC & HTML 5
Daniel Fisher
 
Training: MVVM Pattern
Betclic Everest Group Tech Team
 
Vue micro frontend implementation patterns
Albert Brand
 
Introduction to Angular Js
Professional Guru
 
Mvc 130330091359-phpapp01
Jennie Gajjar
 
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Ad

Recently uploaded (20)

PDF
July Patch Tuesday
Ivanti
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
July Patch Tuesday
Ivanti
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Ad

"Umbraco MVC - a journey of discovery" - Lotte Pitcher

  • 1. Umbraco MVC A journey of discovery Lotte Pitcher
  • 2. Session Contents Included: Not Included: • Introduction • Best Practises for Umbraco MVC – MVC and Web Forms • Umbraco MVC – Walkthrough a sample site • Pure MVC techniques – Plugging into sample site – J&J are doing a session later • Code First – Or any other solution for strongly typed models for your content
  • 3. MVC • Model-View-Controller Generated designer file • Obligatory Diagram Page.aspx Page.aspx.cs • Learning recommendation – Pluralsight course – MS free 6 hour video online http://www.microsoftvirtualacademy.com/training-courses/ developing-asp-net-mvc-4-web-applications-jump-start
  • 4. Common Features • Alternative to Web Forms, not a replacement • ASP.Net framework features available to both: – – – – – Authentication (forms/windows) Membership and Roles Caching Session and Profile management Configuration system
  • 5. Some Key Benefits of MVC • Full control over HTML – No more <asp:Panel runat=“server”></asp:Panel> – Easier to integrate JavaScript frameworks • No viewstate – Smaller page sizes • Testable – Anthony Dang‟s session
  • 6. MVC v Web Forms Summary • Learning curve with MVC • With Umbraco MVC this is small • Quote from Shannon at CG13 – Only reason not to do MVC is if you don‟t have the resources for your team to learn it
  • 7. Umbraco MVC Demo • Simple site – Home Page – About Page – Contact Us Page • Umbraco back office – Should all look pretty familiar
  • 8. How was this set up? • Visual Studio – File > New Project > ASP.Net MVC 4 Web Application (Empty) • Add Umbraco via Nuget – Package manager console PM> Install-Package UmbracoCms • Install Umbraco – As usual by loading in browser and following on-screen instructions • Initial Configuration – Set up doc types – Bring in assets (css, scripts etc)
  • 9. Adding Templates • Set default render engine to MVC – ~/config/umbracoSettings.config <defaultRenderingEngine>Mvc</defaultRenderingEngine> • View overrides a master page of same name – ~/masterpages/_Layout.master would be superceded by ~/views/_Layout.cshtml • Good way to get going – „convert‟ existing master page • Cheatsheet to help you – http://our.umbraco.org/documentation/cheatsheets/Masterpages 2Views.pdf
  • 10. Demo Site Templates • Review the templates (views) in the demo site – ~/Views/_Layout.cshtml – ~/Views/HomePage.cshtml – ~/Views/Partials/PrimaryNavigation.cshtml • Our Umbraco has useful documentation – our.umbraco.org/documentation/reference/templating/Mvc – Plus on all other aspects of Umbraco MVC
  • 11. View Locations • Several places – discover by calling a missing view
  • 12. Contact Form using a Surface Controller • ~/Models/ContactFormModel.cs – The model that defines the data that we want to collect • ~/Controllers/ContactFormController.cs – Must inherit from Umbraco.Web.MVC.SurfaceController – public ActionResult RenderForm() • Child Action method for displaying view – public ActionResult HandleForm(ContactFormModel model) • Method to handle posted data • ~/Views/ContactForm/RenderForm.cshtml – Html.BeginUmbracoForm<ContactFormController>(“HandleForm”) • ~/Views/ContactPage.cshtml – Html.Action(“RenderForm”, “ContactForm”)
  • 13. Route Hijacking • By default all of the front end routing is executed via the Umbraco.Web.Mvc.RenderMvcController Index action • “Hijacking” allows more control over how pages are rendered • Controller should have the name of DocTypeAliasController and inherit from Umbraco.Web.Mvc.RenderMvcController – E.g. ~/Controllers/StatsPageController.cs • Override the Index action • See documentation on Our for more examples and options – E.g. how to call methods dependent on the template being used
  • 14. MVC Features • Data Annotations • Unobtrusive Validation • Display Modes • Display and Editor Templates • Custom Attributes • ViewBag • Scaffolding • Bundling and Minification • Areas
  • 15. Data Annotations • Model/ContactFormModel.cs – – – – Display name for SignUp [Display(Name = "Newsletter?")] Name is required (with default error message) [Required] Email is required (with bespoke error message) Email must be valid (regular expression) [RegularExpression] • View in browser – SignUp now says „Newletter?‟ – Can‟t submit an empty form – Can‟t submit an invalid email address • Notes – Custom annotations can defined – Foolproof is example of nuget package you can add for more advanced validation – e.g. RequiredIf
  • 16. Unobtrusive Validation • Currently validation done after post • For unobtrusive (client-side) install 2 Nuget packages: – jQuery – Microsoft.jQuery.Unobstrusive.Validation • Allow in web.config – <add key="ClientValidationEnabled" value="true" /> – <add key="UnobtrusiveJavaScriptEnabled" value="true" /> • Reference scripts in ContactPage.cshtml (or in master layout if used a lot) • ContactUs.css has css for styling error messages and invalid controls
  • 17. Display Modes • MVC has a default display mode already called „Mobile‟ – – – – iPhone is viewed as Mobile, iPad isn‟t Copy _Layout.cshtml and rename _Layout.Mobile.cshtml Make a difference to the mobile layout View site using browser that is simulating a mobile • Allow switching between modes – Enable Controllers/ViewSwitcherController.cs – Views/Shared/ViewSwitcher.cshtml • ViewContext.HttpContext.GetOverriddenBrowser().IsMobileDevice – Add html helper to footer in both layouts • Notes – If „Mobile‟ version does not exist then just uses standard – Can specify own display modes and rules as required
  • 18. Display and Editor Templates • Views/ContactForm/RenderForm.cshtml – Has examples of both @Html.EditorFor and @Html.DisplayFor • Want to replace all tick boxes for bools with dropdown – – – – Views/EditorTemplates/Boolean.cshtml Views/DisplayTemplates/Boolean.cshtml Should now be dropdown and text for display not box Display modes also work – Boolean.Mobile.cshtml • Notes – Have a template that matches the name of the „type‟ of the property for all properties, – Or annotate specific properties with [UIHint(“TemplateName”)]
  • 19. HTML5 and Custom Attributes • E.g: you want to have styling control over Email field • Option 1 – HTML 5 attribute – [DataType(DataType.EmailAddress)] annotation causes MVC to output input type=“email” not type=“text” – Can then style against input[type=email] • Option 2 – Specify CSS – Remove DataType annotation – Views/ContactForm/RenderForm.cshtml – Change @Html.EditorFor(x => Model.Email) to @Html.TextBoxFor(x => Model.Email, new { @class = "email"})
  • 20. ViewBag • ViewBag is a dynamic object – Can add properties to it in the controller • ViewBag.PageVisits = 123; – Views can read and update the ViewBag – NB partial views only get passed a copy of the ViewBag, so they can access it, but not update it • Controller – This is the “recommended” way to pass the data needed to populate a dropdown list if needs to be got from database • View – “Standard” way for a view to set the page title that is then rendered by layout
  • 21. Scaffolding • A technique to quickly generate a basic outline of your software that you can then edit and customise • NuGet package: UmbracoCms.Scaffolding – Compilation error after installing? Shut VS and re-open – This will create a model, surface controller and view • For example – PM> Scaffold SurfaceController ContactForm2 Name, Email, Signup – Generates 3 files with a place to start from: • ~/Models/ContactForm2Model.cs • ~/Controllers/SurfaceControllers/ContactForm2SurfaceController.cs • ~/Views/ContactForm2Surfce/ContactForm2.cshtml • Customise templates in ~/CodeTemplates
  • 22. Bundling and Minification • Combine and minify script files and stylesheets to improve request load time • Debug mode true? – Renders individual source versions so editing easier • Debug mode false? – Should render bundled/minified – If change made to a bundled file, the bundle link gets recreated • Blog from The Outfield – http://www.theoutfield.net/blog/2013/09/mvc-unobtrusivevalidation-in-umbraco • Optimus package for doing this via the back office – http://our.umbraco.org/projects/developer-tools/optimus
  • 23. Areas • An Area is “partition” of an MVC site – Own folders for Models, Views and Controllers – With some „tweaks‟ can use the same Layouts as Umbraco pages • Why? – If you have existing MVC functionality you want to bring into an Umbraco MVC site, – or you want to develop an section of the site that does not need any content management • Example – Members only area that we want to develop as quickly as possible – client has no requirement for editing pages • Will be a blog post!
  • 24. Summary • Have a go - start with converting an existing master page to a view • Lots of MVC features that can plugged in when you are ready • Go to “J&J‟s” session on their hybrid MVC framework session for their thoughts on best practises • Resources (follow @lottepitcher): – This presentation on SlideShare – The finished Visual Studio solution is available here: https://www.dropbox.com/s/le5t9wqldg2zx2u/UKFestivalMVC.zip

Editor's Notes

  • #2: Welcome to this session on Umbraco MVC.I’m Lotte Pitcher, a director of PAM Internet: a web development company in Shoreditch, London.
  • #3: Let’s kick off with a review of what this session will cover:A brief intro into MVC and how it compares to web formsA walkthrough of a simple Umbraco MVC siteAnd finally some MVC techniques and features that can be used in an Umbraco MVC siteI am NOT coveringBest practises: there is another session from J&amp;J that covers thisOr any thoughts on how to have strongly-typed models for your document types: this would fill an entire session in its own right!
  • #4: So MVC – a pattern that separates an application into three main components: the Model, the View, and the Controller. Here’s a diagram that I don’t think explains much at all but appears to be obligatory for any MVC-related presentation! Easiest to explain it in terms of web forms:Model – class defining the data we want to move around – page.aspxController – class with the methods that prepares the model, decides which view to render and handles any posts – page.aspx.csView – renders the user interface, usually HTML – designer file generated automaticallyFor formal learning about MVC, I recommend these two resources:Pluralsight courseMicrosoft free 6 hour video – just have to put up with them saying “yup”, and “exactly” all the time
  • #5: Microsoft are keen to stress that MVC is an alternative to Web Forms, not a replacement. SharePoint, after all, is built using web forms so they have a huge amount invested in it.Both MVC and Web Forms are integrated with some common ASP.Net features:
  • #6: Some of the Key Benefits of MVC over Web FormsFull control over HTMLYou don’t have to fight with server-generated HTML. For example in web forms, you have to know that &lt;asp:Panel&gt; renders as a div, unless, of course, the GroupingText property is specified, in which case it renders as a fieldsetWith MVC you use the HTML you want:Downside that you might have to work a little bit harderUpsides: far more likely to be able to just plug in any prototype code that you are given, and javascript integration is a lot easierStatelessMVC is stateless, arguably matching the true nature of the web, so no more huge viewstates to bloat your page sizesYou can dynamically add controls client-side, unlike web forms that needs them to exist before postbackTestableEach separate part is testableAnthony Dang’s session I believe covers this
  • #7: So in summaryThere is a learning curve with MVCBut, as I am hopefully about to show, with Umbraco MVC you can get started without understanding the full MVC frameworkI think I remember Shannon (from Umbraco HQ) saying that he thought the only reason NOT to use MVC in Umbraco is if you don’t have the resources for your team to learn it.
  • #8: Right, time to see the demo site [switch to Chrome]This is the simple site that I built to support this presentationWe have some common layout: header with a text logo, tagline, and menu; and a footerThe home page content is this content hereThe About page is standard page, again just with some rich html contentA Contact form: this is asking the user for their name, email and if they want to signup for a newsletter. Clicking the button just goes to a thank you pageLet’s ignore the Stats page for the momentIn the back officeIn the Developer section I added uComponents, obviously, and I think just one custom data type of Toggle BoxIn the Settings section:Document Types – we have a master content type of ‘Base Page’ with properties that all pages should have (adds the SEO and Navigation tabs), and then a document type for each pageTemplates: we have a Master template called _Layout, all our page templates use this. We call our master template _Layout as this is an MVC standard that we are used to, but you can of course call your templates whatever you want. I shall look at the contents of templates later.Then to the Content tree:Home – has its own content, plus a tab with some site level content (the Site Layout tab) – specifying the Logo text and tagline in the common header, and the copyright text: note we’ve used raw HTML in this text boxAbout – just content: a heading and a rich html controlContact – contact form, with child thank you page. The contact form has a property (using the Content Picker data type) to specify what page the user should be shown after successfully completing a contact formSo far this should all look pretty familiar! [Back to PPT and show rest of slide]
  • #9: So how was this set up?In Visual Studio File &gt; New Project &gt; Selected the ‘ASP.Net MVC 4 Web Application template’ with no contentThen added Umbraco via NugetRan the website and completed the install of Umbraco following the onscreen instructionsAnd then doing the initial configuration which usually involvesSetting up the document typesBringing in the assets (stylesheets, scripts etc). The demo site uses a simplified version of the HTML5Up free template “Verti”I understand that work is being done on a more advanced / easier / sophisticated way (not sure of the best word!) for starting a new Umbraco project. Something to keep a watch on Twitter for!
  • #10: And now to the interesting – ie MVC specific – bit: templates!The first thing to do is set the default render engine to MVC, a setting in umbracoSettings.config. This tells Umbraco that when you add a new template in the back office, you want to create a razor view (.cshtml) not a master page You can have a masterpage and a view with the same name. If so, Umbraco will use the view in preference to the master page. This gives us a good way to get started: we can convert existing master pages to a view, one-at-a-time.Let’s say you have a master page called Page (i.e. Page.master)Create a view in the views folder with the same name (i.e. Page.cshtml), this will be rendered in preference to your master pageYou should use the cheatsheet on Our Umbraco to see how to translate master pages into views [pause and open pdf]. This is the cheatsheet. For exampleThis is how an umbraco:item control translates into the Umbraco.Field methodPlaceholders are replaced with sections
  • #11: Now let’s look at the templates that are used in the demo site [switch to VS]Start with the view that renders the home page: Views/HomePage.cshtmlAll views must inherit from Umbraco.Web.MVC.UmbracoTemplatePage. This exposes various properties for us, such as:@CurrentPage – dynamic representation of the current page model, used here to display the heading property@Umbraco – contains many helper methods, for example this one: Umbraco.Field – the MVC equivalent of Umbraco:Item – used here to render the bodytext propertyThis view uses a master template, specified using the MVC “Layout” property – the equivalent of a nested master pageNow let’s look at the master template: _Layout.cshtmlAgain, this inherits from UmbracoTemplatePageAs this is our master view, we use “Layout = null” to indicate that no parentWe get the node at the top of our content tree: CurrentPage.AncestorOfSelf(1) so we can display its content on every page In the head section we use the Umbraco property to render some properties of the current pageDisplay some properties from the rootnode dynamicNow here’s our first use of a Partial viewI guess they are the equivalent of a user control in web forms. You use a partial view so it can be reused in this or other applications, or just to stop the views getting too long and hard to understandIf you create a partial view via the Umbraco back-office, the view is created in the ~/Views/Partials folder. My Visual Studio doesn’t appear to ‘like’ this location, which is why the view name appears in red. The page works, as you’ve seen, so this can be ignored. But if it offends you, you could always specify the full file path of the view as in the commentLet’s look at the Partial view [in Partials folder]Expects to be passed a model of type IPublishedContentDraws a unordered list of nodes under the root node – the same sort of razor that has been supported in Umbraco since v4.7 I thinkBack in _Layout.cshtml, we are using a Html helper method to render the partial view “PrimaryNavigation” and passing it the model that it needs: Model.Content (this is the IPublishedContent property of our model)RenderBody()This method must be present in a master view to indicate where the nested view content should be rendered. When the home page displays, for example: the contents of HomePage.cshtml is rendered, and passed up to the master page and displayed in place of RenderBody declaration.By default, @rootNode.copyrightText would be HTML encodedThe HTML helper method Raw prevents this from happening so our copyright symbol is being rendered, and we’re not seeing &amp;copy; on the pageSections can be used in layoutsEquivalent of using web forms placeholdersHere is one at the bottom of the page that would allow nested views to output content just before the body tag ends[Back to PPT]
  • #12: As explained before, partial views added via the back office get put in a folder called ‘Partials’.When Umbraco tries to render a view, it will check several folders for the view of the specified name. A quick way to see this is to call a view that doesn’t exist. For example, if we didn’t have a view called PrimaryNavigation, the page would load with this error.
  • #13: Now let’s look at how the Contact Form works [switch to VS]First up, we need a model, which we are calling ContactFormModel (in the Models folder)This class defines the data that we want to handle3 publics: 2 strings and a boolean, very simpleThen we need a controller, called this ContactFormController (in the Controllers folder)Class must inherit from Umbraco.Web.Mvc.SurfaceController (SurfaceController is an MVC controller that knows about the Umbraco installation). This means:Umbraco sorts out the routing for you (i.e. how the http request reaches this method)We can interact with our Umbraco front-endRenderForm method – our method to render the form ready for user inputChildActionOnly annotation means you can only use this method to render a portion of the page (like a web forms user control)Our method creates a new instance of our model and sets a default for one of the propertiesPasses model to a view – no name needs to be specified if use same name as method in expected location – namely ContactForm folder, file called RenderForm.cshtmlWe could have specified either a different view name in that folder, or a completely different view location. Unless there is a good reason not to, I recommend always using the names expected by convention to keep things as simple as possible, and predictable for other developers.Let’s look at the view: Views folder: /ContactForm/RenderForm.cshtmlThis view expects a type of ContactFormModelUses the helper method BeginUmbracoForm to specify the controller and the method that the user data should be posted to. A &lt;form&gt; tag is started with this using declaration, and an end form tag rendered when it finishes.Html helpers to draw the labels, editor controls and validation messages for each property of our modelStandard html button to cause the form to submit (could be a javascript call)Finally we need to actually get this on our contact page: Views/ContactPage.cshtmlHtml helper method to display the output of the RenderForm Action in the ContactForm controllerSo let’s just look at this in the browser again – a contact form with this section being rendered by the RenderForm actionWhen the button is pressed the data is sent to the method specified in the BeginUmbracoForm declaration [show RenderForm.cshtml again], for us this is the HandleForm method in the ContactForm controllerControllers/ContactFormController.csHandleForm method[HttpPost] indicates this method can only be called for POST not GET requestsAt this point it is useful to understand how MVC binding worksRenderForm.cshtml uses various HTML helper methods: including Html.EditorForThis results in form fields being written to the browser with name=property_name [show in source][Back in VS] Our HandleForm method declares that it expects a single parameter of type ContactFormModel. The MVC Binder will then create a new instance of that type and set any properties whose name is found in the posted data. So if the user entered ‘Fred’ into the name field, after binding the Name property of model would be “Fred”The binder ignores any form fields whose name does not correspond to a property of the expected modelSo long as the posted Request.Form data has the correct key for the property name, the property value will be set. So we could have used client-side Javascript to render the html for the form-fields: the binding would still work. Back to our method… first we check whether the model is valid (we shall plug in some validation shortly). If the model is not valid: we are just going to reshow the current page (return CurrentUmbracoPage shows the page WITH any user data entered already)If the model is valid, we continue with processing: we should do something, obviously, with the posted data but I’ve not specified what here: maybe email someone, or add to a custom db tableThen we want to redirect the user to the thank you pageSo we ask the current page for its thankYouPage propertyIf this is specified, we get the ID of this page (remember it was specified using a content picker control) and then ask Umbraco to redirect the user to this pageIf no thank you page was specified then we use the RedirectToCurrentUmbracoPage method to reshow the current page with a blank form[Back to PPT] So that was an example of a SurfaceController – Umbraco specific MVC
  • #14: The other Umbraco-specific MVC feature I should show is Route Hijacking. Thus far in our demoto render a page all we have to do was create a template and Umbraco handles the rest.This is because by default, all of the front end routing is executed via the Umbraco.Web.Mvc.RenderController Index action (sorry: I realise I use words “action” and “method” interchangeably, I think “action method” is the correct term)But what if we want more control over how a page is rendered? This is where Route Hijacking comes in[Switch to Chrome]I’ve built this Stats page as a quick example of hijacking. To be honest, we’ve not had need of hijacking thus far, so I couldn’t think of a better example to use!At the moment, the Stats page is just a standard page, rendering like our home and about pages. But let’s say that I would like this page to display a counter of the number of times that I have visited it in this session.[Switch to VS]The view looks like this (Views/StatsPage.cshtml)The view gets the number of visits from the session variable, and displays it on the page[Show in browser and refresh] – at the moment we aren’t setting this session variableOne way to do this would be to hijack this route. To do this we need to have a controller with the name that matches our document type. [Show in VS] So in our site, this is StatsPageControllerAnd in this controller we need a method that overrides the Index action methodThis method will now be run: so for us here that is incrementing the session counter, and then calling the base method.I now need to build of course [pause] and then let’s refresh the page [pause]Each time the route is hijacked, we are incrementing the session variable, as you can see[Back to PPT] You can have different methods called depending on the template that is being used with this document type: there is information on this on Our Umbraco.
  • #15: So hopefully this is all making sense so far, and you understand how the demo site works.Now I want to show some “pure” MVC features that we can now use in our demo site.
  • #16: Let’s start with Data Annotations. [Browser] – at the moment, our contact form leaves a little to be desired: the label on the SignUp property looks a bit rubbish, and we could really do with some validation to prevent the user from submitting an empty form, and checking that their email address is valid.[VS] lets sort this out by annotating our modelAdd annotations and explainBuildView in browser: sign up now says Newsletter, and we can’t submit an empty form, and we can’t submit an invalid email address[Back to PPT] So that’s how we use data annotations. You can define your own custom annotations, of course, but always worth checking online to see what open source packages there are first.For example Foolproof is a nuget package that will allow you to specify more advanced validation: for example annotating that this property is required only if another property is true.
  • #17: As you probably noticed, the validation is currently being done on post, obviously it would be preferable to trap this client-side– for which we need Unobstrusive ValidationFirst you need to install 2 nuget packages: jQuery and jQuery unobtrusive validation[VS –Demo-ClientValid]Once you’ve done that we need to add two appSettings to web.configWe need to reference the script libraries on the contact page, in the scripts section we defined in master layoutI’m also just going to improve the styling of the error messages in my stylesheet – MVC renders the error message with the class ‘field-validation-error’, and any control that whose property is invalid is rendered with the class ‘input-validation-error’ (this CSS will set any invalid control to have a red border and background colour)[Browser] so let’s reload the page and check that client side validation is now working[PPT]
  • #18: [Demo-DisplayModes]Now to probably my favourite MVC feature – Display Modes, because it’s so easy to use them to make a big difference. MVC has a built-in display mode called Mobile[switch to VS] iPhones are considered as Mobile by default, whereas iPads aren’tCopy _Layout.cshtml and renaming _Layout.Mobile.cshtmlWe now have a second view called _Layout.Mobile.cshtml and I’m just going to display an exclamation mark after the logo text as the difference between the two versions[FF] So here is the site in FireFox – still rendering our original layout. I’m now going to ask FireFox to pretend it is a mobile device, and reload the page – fingers crossed we should now see the exclamation mark to prove that this is now using _Layout.Mobile.cshtml. [VS] You will probably want to allow your users to decide to switch between mobile and desktop view.Enable the controller ViewSwitcherController and buildWe’ve created a partial view, in Shared (as you can also put your partials in here) called ViewSwitcher that uses the Html ActionLink helper to draw the correct hyperlink to call the SwitchView method in the controllerFinally we just need to add | @Html.Partial(&quot;ViewSwitcher&quot;) to both our layouts[Chrome] let’s view the site in Chrome, we should see the link that will enable to user to override their browser settings[PPT]It’s that’s simple: if there is no ‘.Mobile’ version of a the view, then the standard one is used. Works for partial views as well. For example you could have PrimaryNavigation.Mobile.cshtml if you wanted to render different links for mobile views. This would save you from having having to render two versions of the menu and using CSS to hide/show for mobiles.
  • #19: [Demo-Templates]Now let’s look at Display and Editor Templates[Switch to VS] – close all and open Views/ContactForm/RenderForm.cshtmlHere we are using the Html EditorFor helper method and the Html DisplayFor helper method[Chrome] – and currently this is resulting in this contact formWhat if the client decides that they don’t like the tick box and want to display a dropdown with Yes No instead; oh and also thinks – fair enough – that they want to see the text ‘Yes or No confirming the preset value[Back to VS]This is when Display and Editor Templates are usedThe property that we want to change is of type Boolean. So all we need to add is add Display and Editor Templates with the name that matches the property type. The MVC helper methods DisplayFor and EditorFor will then use these templates insteadShared/DisplayTemplates/Boolean.cshtmlShared/EditorTemplates/Boolean.cshtml[Chrome]Let’s reload the page and check it worksIt works with Display Modes too – let’s say on a mobile device we want Y and N, not Yes and No[VS]Shared/DisplayTemplates/Boolean.Mobile.cshtmlShared/EditorTemplates/Boolean.Mobile.cshtml[Chrome]Switch to mobile version to prove that is working, and back to desktop[PPT]In this example, that would have changed how EVERY boolean property was rendered by the MVC helper methods DisplayFor and EditorFor in the website. If you want a property to use a specific display or editor template, use the UIHint data annotation and specify the name of the template
  • #20: Demo-AttribNow let’s say that you want to have styling control over how your email field is rendered. Two options:First option is to tell MVC that this is an email field using the correct data annotation[VS] close allModels/ContactFormModel.csAdd annotation to email fieldBuild[Chrome]Reload page and look at source: this is now rendering as type Email, so you can then style inputs of type email[PPT]Option 2 is to specify the CSS directly[VS]Remove dataType annotationViews/ContactForm/RenderFormReplace @Html.EditorFor(x =&gt; Model.Email)to @Html.TextBoxFor(x =&gt; Model.Email, new { @class = &quot;email&quot;})This will render a textbox with the CSS class of ‘email’[PPT]