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 HomeControllers‘ Form() 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:
To support jQuery UI we need to add a reference to Scripts/jquery-ui.js in the _Layout.cshtml view:
- The progress dialog is initialized with some custom options (disable dragging, using modal mode, disable close button, …).
- 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.