Computer Magic Logo

Sunday, November 22, 2015

Published by Aristotelis Pitaridis

Now that we defined our model, let’s create the view which will be used in order to collect the user’s information. We create a new partial view and we use the name ContactForm.

@inherits Umbraco.Web.Mvc.UmbracoViewPage<ComputerMagic.Models.ContactFormViewModel>

@if (TempData["success"] == null)
    using (Html.BeginUmbracoForm<ComputerMagic.Controllers.ContactFormSurfaceController>("HandleFormSubmit"))

        @Html.TextBoxFor(m => m.Name, new { @Class = "name", placeholder = "Name" })
        @Html.ValidationMessageFor(m => m.Name)
        <br />

        @Html.TextBoxFor(m => m.EMail, new { @Class = "email", placeholder = "E-Mail" })
        @Html.ValidationMessageFor(m => m.EMail)
        <br />

        @Html.TextAreaFor(m => m.Message, new { @Class = "message", placeholder = "Your Message" })
        @Html.ValidationMessageFor(m => m.Message)
        <br />

        <button id="contact-submit" type="submit">Send</button>
    <p>We will be in touch soon.</p>

At the top of the partial view we define the model that we will use for our form. In our example we use the ContactFormViewModel that we previously created. The first thing that we check is the TempData["success"] to see if it has a null value. We will define it in the controller later and it will contain a not null value in case that the user has submitted successfully the data to the controller. If it contains a not null value we just display the "We will be in touch soon." Message.

In order to display the form we use the BeginUmbracoForm html helper method which will generate the form for us and we define the name of the controller that we will generate which is ContactFormSurfaceController and the action inside the controller which will get the submitted information which is going to be the HandleFormSubmit.

Inside the form we have used the AntiForgeryToken html helper which will make sure that the form will be protected against cross-site request forgery.

After that for each of the model properties we create a pair of input control with a validation message for the property. The TextBoxFor and TextAreaFor html helpers will generate the required html code so that the suitable html control will appear in the specified position. For each of the controls we have defined the classes name so that we will be able to format them in our CSS file. We also defined the placeholder property for each of these controls. The ValidationMessageFor defines the position that the error message will appear on the screen.

Finally we have a submit button which will allow the user to submit the information to the controller.