Using Ajax.BeginForm – ASP.NET MVC3 Ajax – Part III

In my previous blog posts Part 1, Part 2 we have explored how to use the Ajax.ActionLink() helper method to implement a basic Ajax request. In this blog post we have are going to see an another useful helper method Ajax.BeginForm()

We will be implementing the following scenario using the Ajax.BeginForm(). The scenario would be having a view consisting of a simple form with name and email field.

Upon clicking the “Submit” button, the data will be sent back to the server via Ajax Post request and get a confirmation like this.

ASP.NET MVC3 offers an intuitive way to submitting/posting the form data to server via ajax using Ajax.BeginForm helper method. Lets start developing the scenario by first defining the Model (Not using TDD to keep this blog post simple).

To keep things simple, Our PersonalDetailsController will be having only two action methods. One will handling the “Get” request for Creating PersonalDetail and the other one for handling “Post” request for Creating PersonalDetail.

Now, the stage is set to play using ajax. The View for Creating new PersonalDetail using Ajax is similar to that of using ordinary post back except one factor. We need to replace the Html.BeginForm helper method with the Ajax.BeginForm

Ajax.BeginForm method has 11 overloads. On this blog post we are going to use the following overload. Ajax.BeginForm(string actionName, string controllerName, AjaxOptions ajaxOptions)

The actionName and controllerName points to the handler which is going to handle the ajax request and the ajaxOptions defines the behavior of the ajax request. The View for Creating PersonalDetail will look like this

That’s it!! All you need to do is to enclose your form into an Ajax.BeginForm method wired with the necessary configurations. In this example the ajax form method takes care of wiring up submit form action to the given action method of the controller and update the result which it receives from the server using the UpdateTargetId. You can also play with the Ajax request by adding a loading animation as I have mentioned in Part II blog post. Note: Dont forget to add references to the jQuery script files

Summary:

In this blog post we have seen a very basic way to create Ajax forms in ASP.NET MVC3. You can download the source code of this blog post from here

Comments