In this article I will explain a simple tutorial with example on how to use Ajax.BeginForm extension method in ASP.Net MVC Razor.
The Ajax.BeginForm extension method is used to make AJAX calls to Controller’s Action method in ASP.Net MVC Razor.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
Installing and Configuring Unobtrusive AJAX Library
You will need to install the Unobtrusive AJAX Library using the NuGet Package Manager as shown below.
ASP.Net MVC Ajax.BeginForm Tutorial with example
 
The Unobtrusive AJAX Library is needed in order to trigger the OnSuccess event handler of Ajax.BeginForm method in JavaScript.
Once the Unobtrusive AJAX Library is installed, the jquery.unobtrusive-ajax.min.js needs to be inherited in the View.
Then you will need to add the following key to the AppSettings section of the Web.Config file which will make sure that the Unobtrusive AJAX Library is enabled.
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
 
Note: It is very important to perform the above steps in order to use the OnSuccess event handler of the of Ajax.BeginForm method in JavaScript.
 
 
Model
Following is a Model class named PersonModel with four properties i.e. PersonId, Name, Gender and City.
public class PersonModel
{
    ///<summary>
    /// Gets or sets PersonId.
    ///</summary>
    public int PersonId { get; set; }
 
    ///<summary>
    /// Gets or sets Name.
    ///</summary>
    public string Name { get; set; }
 
    ///<summary>
    /// Gets or sets Gender.
    ///</summary>
    public string Gender { get; set; }
 
    ///<summary>
    /// Gets or sets City.
    ///</summary>
    public string City { get; set; }
}
 
 
Controller
Then you will need to add a Controller class to your project. There are two Action methods, one for handling the GET operation while other for handling the POST operation.
The Action method for AJAX POST operation accepts an object of the PersonModel class as parameter. The values posted from the Form inside the View are received through this parameter.
And then same object of the PersonModel class is returned backed to the View as JSON object.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public JsonResult AjaxMethod(PersonModel person)
    {
        int personId = person.PersonId;
        string name = person.Name;
        string gender = person.Gender;
        string city = person.City;
        return Json(person);
    }
}
 
 
View
Inside the View, in the very first line the PersonModel class is declared as Model for the View.
The View consists of an HTML Form which has been created using the Ajax.BeginForm method with the following parameters.
ActionNameName of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
AjaxOptions – It specifies the various properties used for AJAX calls. Following are the three properties used in this example.
1. OnSuccess – Name of the JavaScript function which will receive the response when the AJAX call is successful.
2. OnFailure – Name of the JavaScript function which will receive the response when the AJAX call fails.
3. LoadingElementId – ID of the element which will be displayed when the AJAX call is in progress.
There are three TextBox fields created for capturing values for PersonId, Name and City using the Html.TextBoxFor method. While for capturing the Gender value, a DropDownList with three options is created using the Html.DropDownListFor function.
There is a Submit Button at the end of the Form and when the Button is clicked, the AJAX call is made.
Finally there’s a hidden HTML DIV element which is displayed when the AJAX call is in progress.
@model Ajax_Form_Post_MVC.Models.PersonModel
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
            margin: 0;
            padding: 0;
        }
        table {
            border: 1pxsolid#ccc;
            border-collapse: collapse;
            background-color: #fff;
        }
        table th {
            background-color: #B8DBFD;
            color: #333;
            font-weight: bold;
        }
        table th, table td {
            padding: 5px;
            border: 1pxsolid#ccc;
        }
        table, table table td {
            border: 0pxsolid#ccc;
        }
        input[type=text], select {
            width: 150px;
        }
        .modal {
            position: fixed;
            z-index: 999;
            height: 100%;
            width: 100%;
            top: 0;
            background-color: Black;
            filter: alpha(opacity=60);
            opacity: 0.6;
            -moz-opacity: 0.8;
            display: none;
        }
        .center {
            z-index: 1000;
            margin: 50pxauto;
            padding: 10px;
            width: 130px;
            background-color: White;
            border-radius: 10px;
            filter: alpha(opacity=100);
            opacity: 1;
            -moz-opacity: 1;
        }
        .centerimg {
            height: 128px;
            width: 128px;
        }
    </style>
</head>
<body>
    @using (Ajax.BeginForm("AjaxMethod", "Home",
                    new AjaxOptions
                    {
                        OnSuccess = "OnSuccess",
                        OnFailure = "OnFailure",
                        LoadingElementId = "progress"
                    }))
    {
        <table id="tblPersons" cellpadding="0" cellspacing="0">
            <tr>
                <th colspan="2" align="center">Person Details</th>
            </tr>
            <tr>
                <td>PersonId: </td>
                <td>
                    @Html.TextBoxFor(m => m.PersonId)
                </td>
            </tr>
            <tr>
                <td>Name: </td>
                <td>
                    @Html.TextBoxFor(m => m.Name)
                </td>
            </tr>
            <tr>
                <td>Gender: </td>
                <td>
                    @Html.DropDownListFor(m => m.Gender, new List<SelectListItem>
                   { new SelectListItem{Text="Male", Value="M"},
                     new SelectListItem{Text="Female", Value="F"}}, "Please select")
                </td>
            </tr>
            <tr>
                <td>City: </td>
                <td>
                    @Html.TextBoxFor(m => m.City)
                </td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Submit"/></td>
            </tr>
        </table>
    }
    <div id="progress" class="modal">
        <div class="center">
            <img src="~/images/loader4.gif"/>
        </div>
    </div>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
 
    <script type="text/javascript">
        function OnSuccess(response) {
            var message = "Person Id: " + response.PersonId;
            message += "\nName: " + response.Name;
            message += "\nGender: " + response.Gender;
            message += "\nCity: " + response.City;
            alert(message);
        }
        function OnFailure(response) {
            alert("Error occured.");
        }
    </script>
</body>
</html>
 
 
Screenshot
ASP.Net MVC Ajax.BeginForm Tutorial with example
 
 
Downloads