Shannon Deminick's blog all about web development

Native MVC support in Umbraco coming very soon!

October 31, 2012 00:07

Its been a while since writing a blog post! … but that’s only because I can never find the time since I’m still gallivanting around the globe :P

But this post is about something very exciting, and I’m sure most of you that are reading this already know that with the upcoming Umbraco 4.10.0 release (currently in Beta and downloadable here) we are natively supporting ASP.Net MVC! What’s more is that I’ve tried to document as much as I could on our GitHub docs. Once my pull request is completed the docs will all be available on the main site but until then you can see them on my fork here.

So where to begin? Well, I’m going to try to keep this really short and sweet because I’m hoping you can find most of the info that you’ll want in the documentation.

What is supported?

Everything that you can do in MVC you will be able to do in Umbraco’s MVC implementation. Anything from Partial Views, Child Actions, form submissions, data annotations, client validation to Surface Controllers, custom routes and hijacking Umbraco routes.  If you have used Razor macros before, we support a very similar syntax but it is not 100% the same. We support most of the dynamic querying that you use in Razor macros with the same syntax but to access the dynamic model is slightly different. What is crazy awesome super cool though is that we support a strongly typed query structure!! :) So yes, you can do strongly typed Linq queries with intellisense, no problemo!

Still using Web forms? not a problem, you can have both Web forms and MVC engines running in tandem on your Umbraco site. However, a config setting will set a default rendering engine which will determine whether Web forms master pages or MVC views are created in the back office.

What is not supported (yet)

There’s a few things in this release that we’ve had to push to 4.11.0 due to time constraints. They include: Better tooling support for the View editors in the back office, Partial View Macros and Child Action Macros. Though once you start using this MVC version you’ll quickly discover that the need for macros is pretty small. Perhaps people use macros in different ways but for the most part with the way that MVC works I would probably only use macros for rendering macro content in the WYSIWYG editor.

We support rendering any macros in MVC so you can even render your XSLT macros in your views, but issues will arise if you have User Control or Web form control macros that contain form elements. You will still be able to render these macros but any post backs will not work, and will most likely cause a YSOD. Unfortunately due to the vast differences between how Web forms and MVC work in ASP.Net this is something that we cannot support. The good news is that creating forms in MVC is super easy and makes a whole lot more sense than Web forms…. you can even have more than one <form> element on a page, who’d have thought :P

Strongly typed queries

You can find the documentation for this here but I just wanted to point out some of the differences between the strongly typed syntax and the dynamic syntax. First, in your view you have two properties:

  • @Model.Content = the strongly typed model for your Umbraco view which is of type: Umbraco.Core.Models.IPublishedContent
  • @CurrentPage = the dynamic model representing the current page, this is very very similar to the @Model property in Razor macros

An example is to get the current page’s children that are visible, here’s the syntax for both (and of course since the @CurrentPage is dynamic, you will not get intellisense):

//dynamic access

//strongly typed access
@Model.Content.Children.Where(x => x.IsVisible())

There are also some queries that are just not (yet) possible in the dynamic query structure. In order to get some complex queries to work with dynamic linq, we need to code these in to the parser to create the expression tree. The parser could probably do with more TLC to support things like this but IMHO, we’re just better off using the strongly typed way instead (plus its probably a much faster execution). I’ve listed this as an example in the docs but will use it here again:

//This example gets the top level ancestor for the current node, and then gets 
//the first node found that contains "1173" in the array of comma delimited
//values found in a property called 'selectedNodes'.
//NOTE: This is one of the edge cases where this doesn't work with dynamic execution but the
//syntax has been listed here to show you that its much easier to use the strongly typed query

//dynamic access
var paramVals = new Dictionary<string, object> {{"splitTerm", new char[] {','}}, {"searchId", "1173"}};
var result = @CurrentPage.Ancestors().OrderBy("level")
.Where("selectedNodes != null && selectedNodes != String.Empty && selectedNodes.Split(splitTerm).Contains(searchId)", paramVals)

//strongly typed
var result = @Model.Content.Ancestors().OrderBy(x => x.Level)
.FirstOrDefault(x => x.GetPropertyValue("selectedNodes", "").Split(',').Contains("1173"));

IMHO i much prefer the strongly typed syntax but it’s up to you to decide since we support both structures.


Another class we’ve introduced is called the Umbraco.Web.UmbracoHelper which is accessible on your views by using the @Umbraco syntax and is also accessible on any SurfaceController. This class contains a ton of handy methods, it is basically the ‘new’ Umbraco ‘library’ class (you know that static one that has a lower case ‘l’ :P ) Of course the ‘library’ class will still be around and you can still use it in your views… but you shouldn’t! This new helper class should contain all of the methods that you need from querying content/media by ids, rendering macros and rendering field content, to stripping the html from a string. The library class was designed for use in Xslt where everything from c# wasn’t natively given to you, now with Razor views you have the entire world of c# at your fingertips. So you’ll notice things like the date formatting functions that were on ‘library’ are not on the UmbracoHelper, and that is because you can just use the regular c# way. Though, if you feel inclined that these methods should be on UmbracoHelper, another great thing is that this is not a static class so you can add as many extension methods as you like.  I’d list all of the methods out here but I said I’d keep it short, your best bet currently is to just have a look at the class in the source code, or just see what great stuff shows up in intellisense in VS.


Though we did have another UmbracoContext class, this one is the new cooler one and the old one has been marked as obsolete. This new one’s full name is Umbraco.Web.UmbracoContext and it is a singleton so you can access it by UmbracoContext.Current but normally you shouldn’t have to access it by it’s singleton because it is available in all of your views and SurfaceControllers as a property. For example, to access the UmbracoContext in your view you simply use @UmbracoContext. This class exposes some handy properties like: UmbracoUser, PageId, IsDebug, etc…


If you are interested in MVC and Umbraco, it would be really really appreciated for you to take the time to download the beta, the latest nightlies or source code and give it a shot. Hopefully the docs are enough to get you up and running and if you run into any troubles please log your issues on the tracker. If you have any question, comments, etc… about the source code we’d love to hear from you on the mail list.

Pete will be putting up an MVC getting started post on the Umbraco blog real soon, so watch this space!


Umbraco v5 Surface Controller Forms

November 29, 2011 21:22

This post will show you how to create a form in Umbraco v5 using Surface Controllers. The information in this post assumes that you are familiar with Surface Controllers (see this previous post if not) and with creating forms in ASP.Net MVC.


This post is about developing for Umbraco v5 (Jupiter) which at the time of this post is still under development. The technical details described below may change by the time Umbraco Jupiter is released. If you have feedback on the technical implementation details, please comment below.

Create a model

The easiest way to create a form in MVC is to create a model that represents your form. This isn’t mandatory but then you’ll have to use some old school techniques like getting posted values directly from the HttpRequest object.

An example could be:

namespace MySite.Models
    public class MyTestModel
        public string Name { get; set; }

        public int Age { get; set; }        

Create a Surface Controller

For this example we’ll assume that we’re creating a locally declared Surface Controller (not a plugin, see the previous post for full details).

Some code first and explanation after:

namespace MySite.Controllers
    public class MySurfaceController : SurfaceController
        public ActionResult HandleFormSubmit(
            [Bind(Prefix = "MyTestForm")]
            MyTestModel model)
            if (!ModelState.IsValid)
                return CurrentUmbracoPage();
            //do stuff here with the data in the model... send
            // an email, or insert into db, etc...
            return RedirectToUmbracoPage(
                new HiveId(
                    new Guid("00000000000000000000000000001049")));

Lets break down some parts of the above Controller code:

Namespace: Generally you’ll put your locally declared controllers in the ~/Controllers folder, the above namespace reflects this.

Class: The Surface Controller class is suffixed with the term ‘SurfaceController’. This is a required convention (as per the previous post), without that suffix, the controller will not get routed.

[Bind] attribute: In the code below you’ll see that we are creating the editor with a ‘prefix’ called ‘MyTestForm’. This ensures that each input element on the form will get its name prefixed with this value. For example:

<input type="text" name="MyTestForm.Name" />

This is a recommended practice however it is optional. If you don’t prefix your form controls then you don’t need to use the [Bind] attribute. Here’s a few reasons why this is a recommended practice:

  1. Without the prefix, If there is more than 1 form rendered on your webpage and both are using the MVC validation summary, then both validation summaries will display the errors for both forms. When there is a prefix you can tell the validation summary to only display errors for the form with the specified prefix.
  2. The MVC Html helpers will generate the html id for each element and without specifying a prefix and if you have more than 1 form rendered on your page you may end up with duplicate html element Ids.
  3. If you create a scaffolded form with a custom model object such as doing:

    @{ var someModel = new MyModel(); }
    @Html.EditorFor(x => someModel)

    then MVC will automatically prefix your input fields with ‘someModel’ . For some reason MVC does this when the model name isn’t exactly ‘Model’.

return CurrentUmbracoPage: This method is built in to the base SurfaceController class and simply returns the currently executing Umbraco page without a redirect to it which is generally what you want to do in order to display any validation errors.

return RedirectToUmbracoPage: This method is built in to the base SurfaceController class and performs a redirect to a Umbraco page given an Id which is generally what you want to do when a form submission is successful. (chances are that you wont have a page with a Guid id of 00000000000000000000000000001234…. this is just an example :)

NOTE: There is also a RedirectToCurrentUmbracoPage() method!

Rendering a form

There are a few ways to render a form:

  • Directly in your Umbraco template/view
  • Using a Partial View macro
  • Using a Child Action macro which renders a partial view

Regardless of which you use to render a form, the markup will be very similar. Similar to MVC’s @Html.BeginForm, we have an @Html.BeginUmbracoForm helper:

    var formModel = new MySite.Models.MyTestModel();

@using(Html.BeginUmbracoForm("HandleFormSubmit", "MySurface"))
    @Html.ValidationSummary(prefix: "MyTestForm")
    @Html.EditorFor(x => formModel, "", "MyTestForm")
    <input type="submit"/>

Here’s the breakdown of the above mark-up:

Html.BeginUmbracoForm: A normal MVC form would simply use Html.BeginForm which will create an action attribute for the html form tag with a URL of your controller’s action. In Umbraco however, we want the URL to be posted to the same as the URL being rendered (post back), so the BeginUmbracoForm call handles this all for us. It will create a form tag with the URL of the currently rendered Umbraco node and add some custom hidden fields to your form containing the values of where the data will actually post to (your Surface Controller’s action). The Umbraco front-end route handler will take care of all of this for you.

The parameters passed in to BeginUmbracoForm will differ depending on if your Surface Controller is a plugin controller or a locally declared controller. In this example, its a locally declared controller so we just need to give it the action name and controller name. If its a plugin Surface Controller, you’ll need to give it the action and and the controller ID. There’s also a few overloads so that you can add additional html attributes to the rendered html form tag.

@Html.ValidationSummary: The native MVC ValidationSummary doesn’t let you target specific input tags via prefixes so we’ve created a ‘better’ one that does let you do that. In this example we’re telling the validation summary to only display errors for input values that are prefixed with “MyTestForm” which is real handy if you’re rendering a few forms on the same page and using a validation summary for each.

@Html.EditorFor: This is the native EditorFor method in MVC which lets you supply a prefix name which will be used for all of your input fields. The MVC methods for rendering individual input tags also have an overload to supply a prefix if you choose not to have it scaffold your form for you.

formModel: The above mark-up will scaffold the form for us based on the model that we created previously. This example creates an inline model object (formModel) to scaffold the form but if you had a strongly typed partial view with your model type, you could just as well use the view’s Model property.

And that’s pretty much it! Happy form making :)

Umbraco Jupiter Plugins - Part 5 - Surface Controllers

November 29, 2011 14:31

This is the fifth blog post in a series of posts relating to building plugins for Umbraco v5 (Jupiter). This post will explain what a Surface Controller is, what they can be used for and how to create one.


This post is about developing for Umbraco v5 (Jupiter) which at the time of this post is still under development. The technical details described below may change by the time Umbraco Jupiter is released. If you have feedback on the technical implementation details, please comment below.

Related Posts:

  1. Umbraco Jupiter Plugins – Part 1
  2. Umbraco Jupiter Plugins – Part 2 – Routing
  3. Umbraco Jupiter Pluings – Part 3 – Trees
  4. Umbraco Jupiter Pluings – Part 4 – Editors

What is a Surface Controller?

A Surface Controller is an MVC controller that interacts with the front-end (or render layer) of Umbraco. An example of a Surface Controller could be a controller that has a Child Action used to display a Twitter Feed, or a controller that has an Action to accept some posted information from a form. Child Actions on Surface Controller will probably be primarily used for Child Action Macros in Umbraco v5.

Since Surface Controllers are plugins, this means that you can create a package that contains Surface Controllers to distribute whatever front-end functionality you like to Umbraco developers. Surface Controllers, just like Tree Controllers and Editor Controllers get automatically routed for you.

Creating a Surface Controller

Important convention: All Surface controller names MUST be suffixed with ‘SurfaceController’. For example, if you are creating a Surface Controller to display system a Twitter feed, you might call your controller: TwitterFeedSurfaceController. If you don’t follow this convention, you’re surface controller wont be routed.

The first step is to create a class that inherits from the base Surface Controller class:  Umbraco.Cms.Web.Surface.SurfaceController

The next step is to define some MVC Action’s to do whatever it is you’d like them to do. Here’s some examples:

  • Creating an action to partake in a Child Action Macro. To define this is very simple and follows the exact same MVC principles to creating a Child Action… just add a ChildActionOnlyAttribute to your action method:
public ActionResult DisplayTwitterFeed()
  • Creating a child action to simply be used as a normal MVC child action which get rendered using @Html.Action or @Html.RenderAction
  • Create an action to handle some posted form data:
public ActionResult HandleMyFormSubmission(MyFormModel model) 
  • Maybe you’d like to track all links clicked on your page. You could use jquery to update all of your links on your page to point to your custom action URL with the real URL as a query string. Then your custom action will log the real link address and redirect the user to where they want to go.

Plugins vs Non-plugins

A Surface Controller ‘can’ be a plugin, meaning that you can create it as a plugin and distribute it as part of a package. However, if you are creating your own Umbraco website and do your development in Visual Studio like most of us, you don’t need to create a Surface Controller with a plugin definition and install it as part of a package, you can just define it locally just like a controller in a normal MVC project. If you do want to ship your Surface Controller as part of a package then you must attribute your Surface Controller with the SurfaceAttribute, and give it an Id. If you don’t do this then Umbraco will detect that its loading a Surface Controller plugin without an Id and throw an exception.

As a plugin

Standard practice for creating any kind of controller is to put your controllers in the ‘Controllers’ folder (this is not mandatory but a simple convention to follow). So If you’ve created a new project in Visual Studio, you’d create a folder called ‘Controllers’, then create your Surface Controller class with the SurfaceAttribute and an Id:

using System.Web.Mvc;
using Umbraco.Cms.Web.Context;
using Umbraco.Cms.Web.Surface;
using Umbraco.Framework;

namespace MyProject.Controllers
    public class TwitterFeedSurfaceController : SurfaceController


Because this Surface Controller is a plugin, you’ll need to attribute your project assembly (just like when creating Trees or Editor plugins). You can declare this in any of your classes or in the AssemblyInfo.cs file.

[assembly: AssemblyContainsPlugins]

As a locally declared Surface Controller

This is pretty much identical to the above but you don’t have to include the SurfaceAttribute or attribute your assembly. If you’ve got an Umbraco v5 website that you’re working on you should just create a ~/Controllers folder to put your controller in, just as if you were creating a normal MVC project. Then you can create your Surface Controller:

using System.Web.Mvc;
using Umbraco.Cms.Web.Context;
using Umbraco.Cms.Web.Surface;
using Umbraco.Framework;

namespace MyProject.Controllers
    public class TwitterFeedSurfaceController : SurfaceController


Using a Surface Controller

The usage of a Surface Controller really depends on what you’ve created your surface controller to do. Probably the 3 main ways to use them will be:

  • Create a ChildAction Macro by using the Macro UI in the back office and selecting a child action that you’ve declared on your Surface Controller, then render the macro in your template or inline in the WYSIWYG editor.
  • Directly render a child action declared on your Surface Controller by using @Html.Action or @Html.RenderAction
  • Create an Html form to post data to an action on your Surface Controller using @Html.BeginUmbracoForm (more on this in the next blog post!)