Upload
lottepitcher
View
7.531
Download
2
Tags:
Embed Size (px)
DESCRIPTION
Slides from the presentation I gave at the Umbraco UK Festival in November 2013. The accompanying Visual Studio 2012 solution is downloadable from here: https://www.dropbox.com/s/le5t9wqldg2zx2u/UKFestivalMVC.zip (15MB approx) If you have any questions please let me know @lottepitcher
Citation preview
Umbraco MVCA journey of discovery
Lotte Pitcher
Included:
• Introduction– MVC and Web Forms
• Umbraco MVC– Walkthrough a sample site
• Pure MVC techniques– Plugging into sample site
Session Contents
Not Included:
• Best Practises for Umbraco MVC– J&J are doing a session
later
• Code First– Or any other solution for
strongly typed models for your content
• Model-View-Controller
• Obligatory Diagram
MVC
• 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
Page.aspx
Page.aspx.cs
Generated designer file
• 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
Common Features
• 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
Some Key Benefits of MVC
• 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
MVC v Web Forms Summary
• Simple site– Home Page– About Page– Contact Us Page
• Umbraco back office– Should all look pretty familiar
Umbraco MVC Demo
• Visual Studio– File > New Project > ASP.Net MVC 4 Web Application (Empty)
• Add Umbraco via Nuget– Package manager consolePM> 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)
How was this set up?
• 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/Masterpages2Views.pdf
Adding 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
Demo Site Templates
• Several places – discover by calling a missing view
View Locations
• ~/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”)
Contact Form using a Surface Controller
• 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
Route Hijacking
• Data Annotations
• Unobtrusive Validation
• Display Modes
• Display and Editor Templates
• Custom Attributes
• ViewBag
• Scaffolding
• Bundling and Minification
• Areas
MVC Features
• 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
Data Annotations
• 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
Unobtrusive Validation
• 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 Modes
• 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”)]
Display and Editor Templates
• 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"})
HTML5 and Custom Attributes
• 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
ViewBag
• 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
Scaffolding
• 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-unobtrusive-validation-in-umbraco
• Optimus package for doing this via the back office– http://our.umbraco.org/projects/developer-tools/optimus
Bundling and Minification
• 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!
Areas
• 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
Summary