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
    {
        [HttpPost]
        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;
            comment.Publish(author);
            umbraco.library.UpdateDocumentCache(comment.Id);

            // 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
    {
        [Required]
        [Display(Name = "Name")]
        public string Name { get; set; }

        [Required]
        [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; }

        [DataType(DataType.Url)]
        public string Website { get; set; }

        [Required]
        [DataType(DataType.MultilineText)] 
        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

Comments

Connie
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.
22/04/2015
Luke
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.
22/04/2015
Sumit
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
26/07/2016
Cary
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 https://loginaid.org/ gmail login different user In Google Chrome, seek out "Clear browsing data" around the Settings screen.
12/08/2018
Richardcax
Who can help with the problem of potency? What advise a preparation?
16/08/2018
Bryanpip
Get me friends plis
17/08/2018
Richardcax
Who can help with the problem of potency? What advise a preparation?
17/08/2018
Richardcax
Who can help with the problem of potency? What advise a preparation?
23/08/2018
Richardcax
Who can help with the problem of potency? What advise a preparation?
25/08/2018
Richardcax
Who can help with the problem of potency? What advise a preparation?
27/08/2018
Shawnbet
Крутые бонусы https://forummogogo55.ru - 1хБет
29/08/2018
Charolette
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 https://emaillogin.us.com/ 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.
30/08/2018
Shawnbet
Крутые бонусы https://forummogogo55.ru - 1хБет
30/08/2018
cynengefl
Hello. And Bye.
01/09/2018
eliali
Hello. And Bye.
05/09/2018
xaipheira
Hello. And Bye.
05/09/2018
vennnile
Hello. And Bye.
08/09/2018
VadimProSEO
Доброго времени! Хочу Вам предложить свою услугу в помощи продвижения вашего сайта в поисковых системах, недорого, всего лишь за 9700 руб. От Вас нужна лишь ссылка на сайт и ключевые слова в текстовом файле, по которым Вы желаете продвинуться в поисковиках (пример вышлю по электр. почте, если Вам нужно продвижение). Я размещаю вечные ссылки на сайтах и форумах, которые ведут на Ваш ресурс. Мною будет написана статья (грамотно размноженная и "заточенная" под Ваш сайт), а в ней будут анкорные или безанкорные ссылки передавать Вам свой "вес", траст, и ссылочную массу. Тем самым увеличивая траст, доверие поисковиков, быстрое индексирование, рост позиций в поиске, рост ссылочной массы и т.д... Вся работа займет по времени 2-3 недели и Вы увидите отличный результат! Ваш сайт "оживет" в сети интернет! 100% предоплата (Принимаю по карте, Вебмани, ЯДеньги, Киви). Списаться со мной Вы можете по почте proxrum$@$mail.ru с темой "ПРОДВИЖЕНИЕ САЙТА ПО СКИДКЕ" (удалите пожалуйста два символа $). У меня нет выходных, я не компания. Я частник! И работаю, стараюсь, как для себя! P.S. Будет хорошо, если у вас на сайте стоит счетчик Яметрики (там есть важные ключевые фразы) и у Вас есть более удобная связь (скайп, аська, или же вайбер). Спасибо! С Уважением!
10/09/2018
Jasonced
I have found a lot of helpful info on your site this page in particular. Many thanks for sharing. http://protagonistpictures.com/end-blaming-movie-online-games-my-personalized/ http://santiaguado.com/my-story-by-elizabeth-smart-and-chris-stewart/ http://sss333.ru/разное/what-is-a-very-own-paper-together-with-photos http://redkenloft-nn.ru/essay-producing-manual-premium-writing-service/ http://afembud.com/acquiring-urgent-essay-writing-service-university/ https://falconpost.in/2017/12/08/scenario-review-composing-support-how-to-get-a-top/ http://thelocals.io/get-your-papers-completed-in-no-time/ http://www.wlfinancialservices.co.za/2018/07/25/how-to-assess-two-characters-how-to/ http://escuelabiblica.comlu.com/index.php/2018/03/12/acquire-ict-coursework-gcse-essay-help-online/ https://www.hmofurnitureguys.com/analyzing-health-information-credible-essay/
11/09/2018
hario
Hello. And Bye.
12/09/2018
BabloPridi
http://fluidlyfe.org/blogs/107/2758/nateglinide-120mg-original-sur-le-net-baisse-prix-securise-ach http://lydlabs.ning.com/profiles/blogs/sildenafil-ranbaxy-150mg-en-ligne-baisse-prix-commander-visa http://hellyeahband.ning.com/profiles/blogs/sildenafil-jubilant-pas-cher-achat-sur-internet-paiement https://www.madmorning.com/blogs/2776/429/doxycycline-comprar-en-una-farmacia-online-aprobada-nicaragua http://quainv.com/blogs/post/30673#sthash.Fuy2Wzvd.VRspSk9t.dpbs http://www.godry.co.uk/profiles/blogs/clomiphene-50mg-o-achat-baisse-prix-clomiphene-inde-pas-cher https://www.olliesmusic.com/blog/19509/sitios-de-confianza-para-comprar-generico-naltrexona-50mg-entrega-rГЎpida-es/ http://techakhil.byethost4.com/ques2ans/index.php?qa=7235&qa_1=phenazopyridine-200mg-ligne-mastercard-pyridium-generique
17/09/2018
Normanambug
sanariu liga http://lt.1-fabrika.ru/sitemap.xml sanariu skausmas gydymas reumatoidinis artritas gydymas http://www.lt.1-fabrika.ru/sitemap.html kelio sanario skausmas vaistai vaistai nuo sanariu skausmo ir uzdegimo http://lt.1-fabrika.ru/sitemap.html artritas gydymas sanariu uzdegimas http://www.lt.1-fabrika.ru/ reumatoidinis artritas vaistai poliartroze http://www.lt.1-fabrika.ru/sitemap.xml sanariu skausmas gydymas
19/09/2018
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
Tags
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
Categories
App Development
Event
Game Development
Mapping
Modelling
Programming
Review
Robotics
Tutorial
Web Development