ASP.NET MVC 3: Using JSON result for jQuery Ajax Forms validation

This blog post is my third blog post about jQuery Ajax forms with ASP.NET MVC 3.

This third post shows how to customize the way the validation result is handled on the client side. The first post about jQuery Ajax forms with ASP.NET MVC 3 describes how to use partial page updates to avoid complete page reloads after submitting the form. In detail, the server validates the (form) data and returns HTML that either contains the form including server side errors or a success message and on the client side this HTML code is used to replace the old form with. Using this technique there is no way to customize the handling of the success message; for example it could be desirable to show the success message in a popup instead of replacing the form.

To make this flexibility possible the server’s response is changed from (pure) HTML code to a JSON array containing to values:

  1. A boolean that indicates whether the server side validation was successful
  2. A string that contains (depending of the validation result) the HTML code of the form with server side errors or the success message

To enable the server to create a JSON array containing the (rendered) HTML code of a view we will use the extension method RenderPartialViewToString() that I’ve described here.

We start with the source code of the second post and change the HomeController‘s Form action to look like this:

[HttpPost]
public ActionResult Form(ValidationModel validationModel)
{
  Thread.Sleep(2000); // Fake processing time
  if (!ModelState.IsValid)
  {
    return Json(new object[] {false, this.RenderPartialViewToString("Partial/_Form", validationModel)});
  }
  return Json(new object[] {true, this.RenderPartialViewToString("Partial/_Success", validationModel)});
}

On the client side we add a new “success dialog”

<div id="SuccessDialog" style="text-align: center; padding: 50px;">
    <div id="SuccessContainer"></div>
</div>

and some jQuery JavaScript that initializes this dialog:

// Initialize success dialog ...
$("#SuccessDialog").dialog({
  autoOpen: false,
  draggable: false,
  modal: true,
  resizable: false,
  title: "Success",
  buttons: [
    {
      text: "Continue",
      click: function () { $(this).dialog("close"); }
    },
    {
      text: "Reload",
      click: function () { location.reload(); }
    }
  ]
});

In this example we add two buttons to the dialog, one for closing the dialog and continuing editing and one to reload the page.

In a last step we adapt the success handler of the jQuery Ajax post to process the JSON array returned by the server:

success: function (data) {
  if (data[0]) {
    $("#SuccessContainer").html(data[1]);
    $("#SuccessDialog").dialog("open");
   } else {
     $("#FormContainer").html(data[1]);
     $.validator.unobtrusive.parse("form");
   }
}

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

Summarized all three blog posts have shown how to build Ajax’s forms with ASP.NET MVC 3 supporting client side and server side validation, partial page update and a customizable way how to send data to the server and how to handle the server’s response on the client side.