Using Ajax.BeginForm in MVC


This article demonstrates how to use Ajax.BeginForm form in MVC, describes details about Ajax.BeginForm form, When to use and how to use this and why we will use Ajax.BeginForm for instead of HTML.BeginForm

Getting Started

When To Use
Ajax.BeginForm is used in the scenario, when you want your web page should not refresh when you submitting server side code. it also helps update part of page without refreshing the web page. This scenario has been demonstrates in this article.

Difference Between Ajax.BeginForm and HTML.BeginForm
In this section we will see, why we should use Ajax.BeginForm over HTML.BeginForm

  1. Won't redirect the form even you do a RedirectAction().
  2. Will perform save , update and any modification operations asynchronously.
  3. Validate the Form using FormMethods - OnSubmit. So you are abort the Post
  4. This creates a form that submits its values using an asynchronous ajax request. This allows a portion of the page to be update without requiring that the entire page be refreshed.

  1. Will redirect the form.
  2. Will perform operations both Synchronously and Asynchronously (With some extra code and care).
  3. Html.BeginForm will always use RouteTable to detrmine the action attribute value.
  4. This will create a form on the page that submits its values to the server as a synchronous HTTP request, refreshing the entire page in the process.

How to Use
Ajax.BeginForm is used within Using block in web page. When using block starts, it renders form start tag and form end tag when using block ends.

 @using (Ajax.BeginForm("ActionName", "ControllerName", new AjaxOptions {"Ajax options" }))  

The Ajax.BegingForm support many parameters, here we will discuss the details in the below.

  1. ActionName: It is string datatype and the name of function want to call in controller.
  2. ControllerName :It is also string datatype and is the name of controller whose function is going to call.
  3. RoutValue:

    it is an object that contains the parameters for a route. The parameters are retrieved through reflection by examining the properties of the object. This object is typically created by using object initialize syntax.

  4. AjaxOption:

    This is the object of AjaxOptions class which comes under System.Web.Mvc.Ajax namespace. It represents option settings for running Ajax scripts in an ASP.NET MVC application. In my another article, we have discussed more details about this option specially properties which controls the activity of Ajax.BeginForm

  5. HtmlAttributes: An object that contains the HTML attributes to set for the element.

 @using(Ajax.BeginForm("UpdateForm","Employee" new AjaxOptions{UpdateTargetId="message"}))   
  @Html.TextBox("textBox1","Enter text")   
  <input type="submit" value="Submit"/><br />  
  <span id="message">Nothing Entered</span>  


In this article we have discussed how to use Ajax.BeginForm, hope this article will make helpful to you.