How to change a form in MVC to submit with AJAX

Posted written by Paul Seal on November 02, 2016 .NET Framework

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

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

3. Add the partial _FormError.cshtml

<h2>Error</h2>
<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, "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddaab8bfaeb4a9b89db4b3aea9bcb1b1a8b0bfafbcbeb2f3aab8bff3b1b2bebcb1">[email&#160;protected]</a>");
            message.Subject = string.Format("Enquiry from {0} {1} - {2}", model.FirstName, model.LastName, model.EmailAddress);
            message.Body = model.Message;
            SmtpClient client = new SmtpClient("127.0.0.1", 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.