Computer Magic Logo
Controller

Sunday, November 22, 2015

Published by Aristotelis Pitaridis

The final step in order to have a workable form is to create our controller. We create a new class called ContactFormSurfaceController and we store it in the App_Code folder of our project.

using ComputerMagic.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Umbraco.Web.Mvc;

namespace ComputerMagic.Controllers
{
    public class ContactFormSurfaceController : SurfaceController
    {
        public ActionResult Index()
        {
            return PartialView("ContactForm", new ContactFormViewModel());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult HandleFormSubmit(ContactFormViewModel model)
        {
            if (!ModelState.IsValid)
                return CurrentUmbracoPage();

            MailMessage message = new MailMessage();
            message.To.Add("EMAIL WHICH WILL RECEIVE THE MESSAGE");
            message.Subject = "New contact request";
            message.From = new MailAddress(model.EMail, model.Name);
            message.Body = model.Message;

            SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
            smtp.Credentials = new System.Net.NetworkCredential("GMAIL ACCOUNT", "PASSWORD");
            smtp.EnableSsl = true;
            smtp.Send(message);

            TempData["success"] = true;

            return RedirectToCurrentUmbracoPage();
        }
    }
}

Our controller inherits from the SurfaceController class. The SurfaceController is a regular ASP.NET MVC controller which is auto routed, meaning that we do not have to setup any custom routes in order to make it work. The controller name has to end with the name SurfaceController and this is the reason that we called our controller ContactFormSurfaceController.

In our controller we have two actions. The first action is the Index which returns the partial view that we created. The second action is the HandleFormSubmit which will handle the form submit. We defined that this action will get a post request and we did this by adding the HttpPost attribute over the action. We also used the ValidateAntiForgeryToken attribute which informs the controller that we used the AntiForgeryToken html helper so that the system will do the required check in order to make sure that the form will be protected against cross-site request forgery.

In the HandleForm we use the IsValid property of the ModelState object to check if the information that the user typed follow the rules that we defined in our model. If the data are not valid we return the currently rendered Umbraco page using the CurrentUmbracoPage member function which will display the error messages.

If the validation was successful then we send a message with the contact request. After the successful sent of the message we set the TempData["success"] to be equal to true so that we will inform the partial view that everything worked and an information message should appear on the visitor’s screen. Finally we use the RedirectToCurrentUmbracoPage which will redirect to the currently rendered Umbraco page so that the message will appear on the screen. In case that we want to redirect to a different URL we can use the Redirect member function as follows:

Redirect("/thanks-for-the-message");

The final thing that we have to make is to add the required code in the view that we want to display the contact form. In order to do it we type the following code:

@Html.Action("Index", "ContactFormSurface")

My view has the following contents.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>@Umbraco.Field("title")</title>
    <meta name="description" content="@Umbraco.Field("description")">
    <meta name="keywords" content="@Umbraco.Field("keywords")">
</head>
<body>
    @Html.Action("Index", "ContactFormSurface")
</body>
</html>

If we try to display the contents of the page we will see the following form.

The form does not look nice because we have to add some CSS but the good thing is that we have a working contact form. If we do not type anything and click the Send button the form will submit the data to the controller and the error messages will appear on the screen.

Now if we type some real information with an incorrect formatted email we will see that the error message for the email will change and the error messages for the other two correct textboxes will disappear from the screen.

If we correct the email and try to submit the form again, the message will be sent and a message will appear on the screen informing us about the successful request.