Asynchronously Submitting a Form and Displaying a Thank You Message in Sitecore MVC

Blog | Technical
Written By: Nabil OrfaliPublished On: Jul 08 2016
lightbulb

I recently had to build an asynchronous form in MVC that switches to a thank you message on successful submission. In this post, we will discuss a way to achieve this using views in MVC.

To get the form to work and display the thank you message correctly, I broke it up into three views:

  1. Main: The main view controls which view is displayed depending on user action.
  2. Form: The form view contains the actual form.
  3. Thank You: The Thank You view contains the thank you message.

In the Main view, we will need to create a container to manage what view should be displayed:

<div ID="yourContainer" class="gsRight form_fields col-sm-6">
    @if (IsPost && ViewData.ModelState.IsValid)
    {
        @Html.Partial("~/Views/Forms/ThankYou.cshtml")
    }
    else
    {
        @Html.Partial("~/Views/Forms/Form.cshtml")
    }
</div>

This way, the Form view will be displayed by default and the Thank You view will be displayed if a postback occurs and the ModelState is valid. This works for the server side case.

There are additional steps in get the form to work asynchronously. First, we need to make some changes to the controller:

  1. Add a route prefix to your controller class:
    [RoutePrefix("forms")]
    public class FormComponentController : DefaultController
  2. Create a route for Form View and the Thank You view:
    [Route("form")]
    public PartialViewResult Form(FormComponent model)
    {
        return PartialView("~/Views/Forms/Form.cshtml", model);
    }
    
    [Route("thankyou")]
    public PartialViewResult ThankYou(FormComponent model)
    {
        return PartialView("~/Views/Forms/ThankYou.cshtml", model);
    }
  3. In your RegisterWebApiRoutes.cs class, add “RouteTable.Routes.MapMvcAttributeRoutes();” before “RouteTable.Routes.MapRoute”.

This way, if you navigate to /forms/form, you will see the Form view, and if you navigate to /forms/thankyou, you will see the Thank You view, we will use this to our advantage to make the form work asynchronously. We will use this script to do so:

$(".{FormClass}").submit(function (e) {
    if ($("#{FormID}").valid()) {
        $.post($(this).attr("action"),
        $(this).serialize(),
        function (data) {
            $("#yourContainer").load('/forms/thankyou');
        });
    }
    e.preventDefault();
});

Where {FormClass} is the name of a class in your form, {FormID} is the ID of your form, and yourContainer is the ID of the view container we created in the Main view.

About the AuthorNabil Orfali
Nabil OrfaliCEO & Founder, Sitecore Strategy MVP
Loading...