YouTube Video Tutorial

This post carries on from my previous tutorial How to create a contact form in Umbraco using MVC and C#

In this video you will see how to change the form to submit using AJAX. I recorded this video live for my livecoding channel.

The code I wrote for this tutorial is further down this post.

1. Update the model

using System.ComponentModel.DataAnnotations;
namespace InstallUmbraco.Models {     public class ContactModel     {         [Required(ErrorMessage ="The first name field is required")]         [Display(Name ="First Name:")]         public string FirstName { get; set; }
        [Required]         [Display(Name = "Last Name:")]         public string LastName { get; set; }
        [Required]         [EmailAddress(ErrorMessage ="You must provide a valid email address")]         [Display(Name = "Email Address:")]         public string EmailAddress { get; set; }
        [Required]         [Display(Name = "Message:")]         public string Message { get; set; }     } }

2. Add the partial _FormSuccess.cshtml

<p>Your message was sent successfully</p>

3. Add the partial _FormError.cshtml

<p>There was an error when trying to send your message</p>

4. Change the Controller to return the success or error partials

using System.Net.Mail;
namespace InstallUmbraco.Controllers {     public class ContactSurfaceController : SurfaceController     {         public const string PARTIAL_VIEW_FOLDER = "~/Views/Partials/Contact/";
        public ActionResult RenderForm()         {             return PartialView(PARTIAL_VIEW_FOLDER + "_Contact.cshtml");         }
        [HttpPost]         [ValidateAntiForgeryToken]         public ActionResult SubmitForm(ContactModel model)         {             if(ModelState.IsValid)             {                 SendEmail(model);                 return PartialView(PARTIAL_VIEW_FOLDER + "_FormSuccess.cshtml");             }             return PartialView(PARTIAL_VIEW_FOLDER + "_FormError.cshtml");         }
        private void SendEmail(ContactModel model)         {             MailMessage message = new MailMessage(model.EmailAddress, "[email protected]");             message.Subject = string.Format("Enquiry from {0} {1} - {2}", model.FirstName, model.LastName, model.EmailAddress);             message.Body = model.Message;             SmtpClient client = new SmtpClient("", 25);             client.Send(message);         }     } }

5. Change the partial _Contact.cshtml to use Ajax.BeginForm

@inherits UmbracoViewPage<InstallUmbraco.Models.ContactModel>
<div id="formOuter">
@using(Ajax.BeginForm("SubmitForm", "ContactSurface", null, new AjaxOptions {     HttpMethod = "POST",     InsertionMode = InsertionMode.Replace,     UpdateTargetId = "formOuter" })) {     @Html.AntiForgeryToken()
    <div class="form-group">         <div class="col-xs-3">             @Html.LabelFor(m => m.FirstName)         </div>         <div class="col-xs-9">             @Html.TextBoxFor(m => m.FirstName)             @Html.ValidationMessageFor(m => m.FirstName)         </div>     </div>
    <div class="form-group">         <div class="col-xs-3">             @Html.LabelFor(m => m.LastName)         </div>         <div class="col-xs-9">             @Html.TextBoxFor(m => m.LastName)             @Html.ValidationMessageFor(m => m.LastName)         </div>     </div>
    <div class="form-group">         <div class="col-xs-3">             @Html.LabelFor(m => m.EmailAddress)         </div>         <div class="col-xs-9">             @Html.TextBoxFor(m => m.EmailAddress)             @Html.ValidationMessageFor(m => m.EmailAddress)         </div>     </div>
    <div class="form-group">         <div class="col-xs-3">             @Html.LabelFor(m => m.Message)         </div>         <div class="col-xs-9">             @Html.TextAreaFor(m => m.Message)             @Html.ValidationMessageFor(m => m.Message)         </div>     </div>
    <button class="use-ajax">Submit</button> } </div>

7. Enable Client Validation and Unobtrusive AJAX

Follow the steps in this post to enable this

8. Update the Contact.cshtml template

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
    Layout = "Master.cshtml";
<div class="container">     @{ Html.RenderAction("RenderForm", "ContactSurface"); } </div>
<script type="text/javascript">     $(document).on("click", ".use-ajax", function (e) {         e.preventDefault();         var form = $(this).closest('form');         $(form).submit();     }); </script>

Any questions?

If you're stuck or if you have any questions, please don't hesitate to get in touch with me. You can do this by commenting on this post, lower down the page, or by commenting on the YouTube video.

If you enjoyed the video and you want to see more, please like it on YouTube and subscribe to my channel.

Want to thank me?

If I've helped you out and you want to thank me, why not buy me a coffee?

About the author

Paul Seal

Umbraco MVP and .NET Web Developer from Derby (UK) who specialises in building Content Management System (CMS) websites using MVC with Umbraco as a framework. Paul is passionate about web development and programming as a whole. Apart from when he's with his wife and son, if he's not writing code, he's thinking about it or listening to a podcast about it.

Related Posts

How to fix corrupt accented characters in Excel for a C# export as CSV

This post will help you fix the issue where you csv export has corrupt characters when opening it in…

Read Post

How to create a dynamic image from multiple images using ImageProcessor

This post shows you how I created a handler to create dynamic header images for my umbraco website u…

Read Post

How to send Slack messages programmatically using C#

In this post I show you how you can send Slack messages programmatically using C#

Read Post

How to fix the SVG 404 error when using Umbraco and Azure Blob Storage

In this post I show you how to solve the SVG 404 error when working with Umbraco and Azure Blob Stor…

Read Post