MVC forms in Umbraco

I've had a lot of trouble working out how to create forms in Umbraco because a lot of the documentation around is either for an old version of Umbraco, using a third party library or just not very helpful!

I've finally found out the trick when working with MVC and surface controllers, and it's very simple once you get to know it, it's definately not as hard a lot of tutorials make it seem.

To get your form working you're going to need to know what a controler is and what it does, so if you don't it's basically an area of code that handles every thing for your forms actions, think of it as the .cs file behind a user control.

For the purpose of this tutorial, I'll show you how to create a comment form, so we're going to start off with creating a partial view in the 'Partials' folder within the 'Views' folder, we'll then add the basic code needed to render the form and link it to a custom surface controller that we'll create in the 'App_Code' folder.

Step 1: Create the partial

Create a partial view in the 'Partials' folder located under the 'Views' folder and name it 'ContactForm' this will be where the GUI part of the form is located, it'll also be what's called from our view page to render the form.

Step 2: Adding the form

To create forms in MVC you can use a neat way of adding elements instead of writing the HTML, for example we can use 'LabelFor', 'EditorFor' and 'ValidationMessageFor' pretty neat right? All of these are preceded by '@Html.' because they're located under the 'Html' class.

See my example below and paste it into a partial view called 'CommentForm' to get started.

@inherits Umbraco.Web.Mvc.UmbracoViewPage
    Layout = null;

@using (Html.BeginUmbracoForm("SubmitComment", "CommentFormSurface"))
  @Html.LabelFor(x => Model.Name)
  @Html.EditorFor(x => Model.Name)
  @Html.ValidationMessageFor(x => Model.Name)

  @Html.LabelFor(x => Model.Email)
  @Html.EditorFor(x => Model.Email)
  @Html.ValidationMessageFor(x => Model.Email)

  @Html.LabelFor(x => Model.Comment)
  @Html.EditorFor(x => Model.Comment)
  @Html.ValidationMessageFor(x => Model.Comment)

This is esseintially the form that people will see and use on our website, it is linked to a model and controller which we will create in step three by means of an inherits statement in the first line which calls the 'CommentFormModel'.


Step Three: Setting up the model and controller

To create the model and controller, you need to create a new class file in the 'App_Code' folder and call it 'CommentController', within this file, you'll add the model and surface controller for your form, copy and paste the below code into the class file to get started.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Umbraco.Web.Mvc;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.web;

namespace LukeAlderton
    /// Comment form controller deals with all comment systems
    public class CommentFormSurfaceController : SurfaceController
        public ActionResult SubmitComment(CommentFormModel model)
            //model not valid, do not save, but return current umbraco page
            if (!ModelState.IsValid)
                return CurrentUmbracoPage();

            // Create the comment and add then data then publish it
            User author = new User(0);
            Document comment = Document.MakeNew(model.Name, DocumentType.GetByAlias("uBlogsyComment"), author, CurrentPage.Children.First().Id);
            comment.getProperty("uBlogsyCommentName").Value = model.Name;
            comment.getProperty("uBlogsyCommentEmail").Value = model.Email;
            comment.getProperty("uBlogsyCommentWebsite").Value = model.Website;
            comment.getProperty("uBlogsyCommentMessage").Value = model.Comment;

            // Add date to the page
            //TempData.Add("SubmissionMessage", "Your comment was successfully submitted");

            // Redirect to current page to clear the form
            return RedirectToCurrentUmbracoPage();

            // Redirect to specific page
            //return RedirectToUmbracoPage(2525);

    public class CommentFormModel
        [Display(Name = "Name")]
        public string Name { get; set; }

        [RegularExpression(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$", ErrorMessage = "Invalid Email Address")]
        public string Email { get; set; }

        public string Website { get; set; }

        public string Comment { get; set; }

This controller is designed to replace the comment function of the uBlogsy comment system which adds a node under the post, within the comments node.

The top class called 'CommentFormSurfaceController' is the surface controller and it handles everything that happens after the form has been submitted, in our case we call the method 'SubmitComment' to add a comment to the post via it.

The lower class called 'CommentFormModel' is our view model and it handles the variables available to us and what they should be displayed as, this model has four variables which can all be accessed via 'model.variablename'.

Step Four: Using the form

To Use the form you simply add the following line into any view in your website:

@Html.Partial("CommentForm",new LukeAlderton.CommentFormModel())

It's as simple as that!

Also note that you can't have a form surrounding your whole page when using this because the form will just post the data as a querystring.

Published at

Tags: Umbraco,MVC

Luke Alderton


Why do you have the TempData line commented out? I am struggling with an issue where I can only get the TempData value to display in the partial that contains the form. It will not display on the parent view, even though that is the next http request.
Connie, TempData is commented out because it's an option if you want to display some custom text when the page reloads. Have you read the TempData value? You can call TempData.Keep("somekeyname"); To make sure it is kept next time it's been read.
BeginUmbracoForm this is an error i am facing again and again in view/partial how to resolve it(System.Web.WebPages.Html.HtmlHelper' does contain defination for BeginUmbracoForm and no extention method 'BeginUmbracoForm' accepting a .....etc
But that problem is really, really bad: the loss of each email. Gmail login email gmail login inbox sign in to gmail While the reason why remain vague - you are not shown a dysfunction of how Google's algorithm made the determination - you will see one of five explanations. The move is in line with Google's existing G Suite Gmail service for businesses, which doesn't scan email data for personalized ads. Gmail sign in to another account gmail login different user In Google Chrome, seek out "Clear browsing data" around the Settings screen.
Who can help with the problem of potency? What advise a preparation?
Get me friends plis
Who can help with the problem of potency? What advise a preparation?
Who can help with the problem of potency? What advise a preparation?
Who can help with the problem of potency? What advise a preparation?
Who can help with the problem of potency? What advise a preparation?
Крутые бонусы - 1хБет
Google's app status dashboard shows that Gmail is experiencing service disruptions and posted this note at 2:12 p. Godaddy email login 365 yahoo email login att email login I know Gmail is free and all; nonetheless it's impossible to really get any attention for what appear like pervasive conditions must affect others. Gmail also tracks the regularity of these contacts and results in a subset of contacts whom you've contacted most. Uf email login cox email login SAN FRANCISCO Microsoft ( MSFT ) can be so confident it contains the Internet's best email service who's is about to spend at least $30 million to deliver its message through the U.
Крутые бонусы - 1хБет
Hello. And Bye.
Hello. And Bye.
Hello. And Bye.
Hello. And Bye.
Доброго времени! Хочу Вам предложить свою услугу в помощи продвижения вашего сайта в поисковых системах, недорого, всего лишь за 9700 руб. От Вас нужна лишь ссылка на сайт и ключевые слова в текстовом файле, по которым Вы желаете продвинуться в поисковиках (пример вышлю по электр. почте, если Вам нужно продвижение). Я размещаю вечные ссылки на сайтах и форумах, которые ведут на Ваш ресурс. Мною будет написана статья (грамотно размноженная и "заточенная" под Ваш сайт), а в ней будут анкорные или безанкорные ссылки передавать Вам свой "вес", траст, и ссылочную массу. Тем самым увеличивая траст, доверие поисковиков, быстрое индексирование, рост позиций в поиске, рост ссылочной массы и т.д... Вся работа займет по времени 2-3 недели и Вы увидите отличный результат! Ваш сайт "оживет" в сети интернет! 100% предоплата (Принимаю по карте, Вебмани, ЯДеньги, Киви). Списаться со мной Вы можете по почте proxrum$@$ с темой "ПРОДВИЖЕНИЕ САЙТА ПО СКИДКЕ" (удалите пожалуйста два символа $). У меня нет выходных, я не компания. Я частник! И работаю, стараюсь, как для себя! P.S. Будет хорошо, если у вас на сайте стоит счетчик Яметрики (там есть важные ключевые фразы) и у Вас есть более удобная связь (скайп, аська, или же вайбер). Спасибо! С Уважением!
I have found a lot of helpful info on your site this page in particular. Many thanks for sharing.разное/what-is-a-very-own-paper-together-with-photos
Hello. And Bye.
sanariu liga sanariu skausmas gydymas reumatoidinis artritas gydymas kelio sanario skausmas vaistai vaistai nuo sanariu skausmo ir uzdegimo artritas gydymas sanariu uzdegimas reumatoidinis artritas vaistai poliartroze sanariu skausmas gydymas
Post a comment
Sit tight...
We're adding your comment.
Thank you.
Your comment has been added.
There's been a problem.
Please try again later.
Share with
Latest Comments
By Normanambug on MVC forms in Umbraco
19 Sep 2018, 04:42 AM
By BabloPridi on MVC forms in Umbraco
17 Sep 2018, 09:23 AM
By hario on MVC forms in Umbraco
12 Sep 2018, 02:41 AM
By Jasonced on MVC forms in Umbraco
11 Sep 2018, 12:17 PM
By VadimProSEO on MVC forms in Umbraco
10 Sep 2018, 14:52 PM
By vennnile on MVC forms in Umbraco
8 Sep 2018, 05:49 AM
By xaipheira on MVC forms in Umbraco
5 Sep 2018, 10:30 AM
By eliali on MVC forms in Umbraco
5 Sep 2018, 05:36 AM
App Development
Game Development
Web Development