Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

Umbraco 7.2.8 Hosting UK - HostForLIFE.eu :: How to Create a Comment Form using MVC in Umbraco

clock October 7, 2015 13:04 by author Rebecca

In this tutorial, I'll show you how to create a comment form using MVC in Umbraco. Many people 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!

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 3: 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!

HostForLIFE.eu Umbraco 7.2.8 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



Umbraco 7.2.8 Hosting France - HostForLIFE.eu :: How to Use Standard Conventions to Create Simple Costum Tree

clock August 21, 2015 07:22 by author Rebecca

This article will explain how to create a simple custom tree an angular editor & dialog using standard conventions. This article doesn't go into detail about how to persist data in your editors, it is a simple tutorial defining how routing interacts with your views and where your views need to be stored.

So all the steps we will go through:

  •     Creating a tree with a menu item
  •     Create an editor
  •     Create a dialog for the menu item

Create a Tree

Step 1

First you need to define a tree class that inherits from Umbraco.Web.Trees.TreeController:

public class MyCustomTreeController : TreeController
{
}

The name of your tree must be suffixed with the term 'Controller'.

Step 2

Next we need to add some attributes to the tree. The first one defines the section it belongs to, the tree alias and it's name. Ensure your tree alias is unique, tree aliases cannot overlap.

[Tree("settings", "myTree", "My Tree")]

The 2nd attribute does 2 things - Tells Umbraco how to route the tree and tells Umbraco where to find the view files. This attribute is not required but if you do not specify it then the view location conventions will not work.

[PluginController("MyPackage")]

There are 2 methods that need to be overriden from the TreeController class: GetTreeNodes & GetMenuForNode. This example will create 3 nodes underneath the root node:

protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
{
    //check if we're rendering the root node's children
    if (id == Constants.System.Root.ToInvariantString())
    {
        var tree = new TreeNodeCollection
            {
                CreateTreeNode("1", queryStrings, "My Node 1"),
                CreateTreeNode("2", queryStrings, "My Node 2"),
                CreateTreeNode("3", queryStrings, "My Node 3")
            };               
        return tree;
    }
    //this tree doesn't suport rendering more than 1 level
    throw new NotSupportedException();
}

Step 3

Next we'll create a menu item for each node, in this case its a 'Create' menu item

protected override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings)
{
    var menu = new MenuItemCollection();
    menu.AddMenuItem(new MenuItem("create", "Create"));
    return menu;
}


That's it, the whole tree looks like this:

[Tree("settings", "myTree", "My Tree")]
[PluginController("MyPackage")]
public class MyCustomTreeController : TreeController
{
    protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
    {
        //check if we're rendering the root node's children
        if (id == Constants.System.Root.ToInvariantString())
        {
            var tree = new TreeNodeCollection
            {
                CreateTreeNode("1", queryStrings, "My Node 1"),
                CreateTreeNode("2", queryStrings, "My Node 2"),
                CreateTreeNode("3", queryStrings, "My Node 3")
            };
            return tree;
        }
        //this tree doesn't suport rendering more than 1 level
        throw new NotSupportedException();
    }
    protected override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings)
    {
        var menu = new MenuItemCollection();
        menu.AddMenuItem(new MenuItem("create", "Create"));
        return menu;
    }
}

Create an Editor

An editor is simply an angular view (html file) so you can really do whatever you'd like! This tutorial will simply create a hello world editor showing the id of the item being edited.

Create a controller

First thing we'll do is create an angular controller for the editor, this controller will be contained in a file found beside the view - the file naming conventions are based on the controller file naming conventions in the Umbraco core.

/App_Plugins/MyPackage/BackOffice/MyTree/mypackage.mytree.edit.controller.js

The controller is super simple, at it is going to do is assign a property to the $scope which shows the current item id being edited:

'use strict';
(function () {
    //create the controller
    function myTreeEditController($scope, $routeParams) {
        //set a property on the scope equal to the current route id
        $scope.id = $routeParams.id;
    };
    //register the controller
    angular.module("umbraco").controller('MyPackage.MyTree.EditController', myTreeEditController);
})();

Create a view

As per the conventions above our editor view will need to be located at:

/App_Plugins/MyPackage/BackOffice/MyTree/edit.html

The view is simple, it is just going to show the current id being edited

<div ng-controller="MyPackage.MyTree.EditController">
    <h1>Hello world!</h1>
    <p>
        You are current editing an item with id {{id}}
    </p>
</div>

Create a Dialog

This is the same principle as an editor, you just need to follow conventions. Based on the above conventions the 'create' dialog view will be located here:

/App_Plugins/MyPackage/BackOffice/MyTree/create.html


HostForLIFE.eu Umbraco 7.2.8 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



HostForLIFE.eu Launches Umbraco 7.2.8 Hosting

clock August 19, 2015 06:56 by author Peter

HostForLIFE.eu, a leading web hosting provider, has leveraged its gold partner status with Microsoft to launch its latest Umbraco 7.2.8 Hosting support

HostForLIFE.eu, a leading Windows web hosting provider with innovative technology solutions and a dedicated professional services team, today announced the support for Umbraco 7.2.8 hosting plan due to high demand of Umbraco users in Europe. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam (NL), London (UK), Paris (FR), Frankfurt (DE) and Seattle (US) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. HostForLIFE Umbraco hosting plan starts from just as low as €3.00/month only and this plan has supported ASP.NET 4.5, ASP.NET MVC 5/6 and SQL Server 2012/2014.

Umbraco 7.2.8 is a fully-featured open source content management system with the flexibility to run anything from small campaign or brochure sites right through to complex applications for Fortune 500's and some of the largest media sites in the world. Umbraco was sometimes unable to read the umbraco.config file, making Umbraco think it had no content and showing a blank page instead (issue U4-6802), this is the main issue fixed in this release. This affects people on 7.2.5 and 7.2.6 only. 7.2.8 also fixes a conflict with Courier and some other packages.

Umbraco 7.2.8 Hosting is strongly supported by both an active and welcoming community of users around the world, and backed up by a rock-solid commercial organization providing professional support and tools. Umbraco 7.2.8 can be used in its free, open-source format with the additional option of professional tools and support if required. Not only can you publish great multilingual websites using Umbraco 7.2.8 out of the box, you can also build in your chosen language with our multilingual back office tools.

Further information and the full range of features Umbraco 7.2.8 Hosting can be viewed here: http://hostforlife.eu/European-Umbraco-728-Hosting

About HostForLIFE.eu

HostForLIFE.eu is an European Windows Hosting Provider which focuses on the Windows Platform only. HostForLIFE.eu deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.asp.net/hosting/hostingprovider/details/953). Their service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, they have also won several awards from reputable organizations in the hosting industry and the detail can be found on their official website.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in