ASP.NET MVC 3: Using jQuery .ajax() function to submit Ajax Form supporting (unobtrusive) Client Side Validation and Server Side Validation

Update 2011-08-09: I’ve written a follow-up blog post which shows how to use JSON to customize the way the server’s response is handled on the client side.

This blog post summarizes how to use jQuery’s .ajax() function to submit an Ajax form in ASP.NET MVC web applications. In ASP.NET MVC you can use the Ajax.BeginForm(…) helper method to create Ajax forms but the options to customize the behavior of the form are limited. In contrast, using jQuery’s .ajax() function one gets full control about the user interface, the way the data is transfered to the server, the error handling and so forth. In this blog post we will use this flexibility to add a progress jQuery UI dialog that is shown while the request is processed by the server.

We will start with the source code created in my previous post “ASP.NET MVC 3: Ajax Form with jQuery validate supporting (unobtrusive) Client Side Validation and Server Side Validation” which can be downloaded from here. It is recommended to read the mentioned previous post to understand how this Ajax form and the validation should work. In the following we will replace the default ASP.NET MVC Ajax functionality with a customized jQuery alternative which will also support client side and server side validation.

The (server) source code remains nearly unchanged, we only add a Thread.Sleep(2000); to the HomeControllersForm() method to fake the time needed by the server to process the request. This ensures, that the progress dialog will be visible and will not disappear immediately after becoming visible since actually the server only needs some milliseconds to process the request.

First, we will replace the Ajax.Html() helper with Html.BeginForm() in Partial/_Form.cshtml view and add the progress dialog to the Index.cshtml view:

<div id="ProgressDialog" style="text-align: center; padding: 50px;">
    <img src="@Url.Content("~/Content/ajax-loader.gif")" width="128" height="15" alt="Loading" />
</div>

To support jQuery UI we need to add a reference to Scripts/jquery-ui.js in the _Layout.cshtml view:

[...]
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-ui.js")"></script>

In a last step we add with some lines of JavaScript code to the Index.cshtml view that implements all the Ajax magic:

<script type="text/javascript">
  $(function () {
 
    // Initialize progress dialog ...
    $("#ProgressDialog").dialog({
      autoOpen: false,
      draggable: false,
      modal: true,
      resizable: false,
      title: "Loading",
      closeOnEscape: false,
      open: function () { $(".ui-dialog-titlebar-close").hide(); } // Hide close button
    });
 
    // Handle form submit ...
    $("form").live("submit", function (event) {
      event.preventDefault();
      var form = $(this);
      $("#ProgressDialog").dialog("open");
      $.ajax({
        url: form.attr('action'),
        type: "POST",
        data: form.serialize(),
        success: function (data) {
          $("#FormContainer").html(data);
          $.validator.unobtrusive.parse("form");
        },
        error: function (jqXhr, textStatus, errorThrown) {
          alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
        },
        complete: function () {
          $("#ProgressDialog").dialog("close");
        }
      });
    });
  });
</script>

Basically, this JavaScript does two things:

  1. The progress dialog is initialized with some custom options (disable dragging, using modal mode, disable close button, …).
  2. Using jQuery’s live functionality an event handler is registered to intercept the form’s submit event to show the progress dialog, post the form data to the server and hide the progress dialog again when the request is processed.

You can download the Visual Studio 2010 project containing all the source code here.