Post Data To Controller Without Page Refresh In ASP.NET MVC

Background

Posting data to the server without whole postback or we can say without page refresh is very important to save the server resources and make application faster. In ASP.NET MVC there are lot of options to achieve this without writing lots of custom code.
Many forum post I read, one common question was the difference between Html.BeginForm and Ajax.BeginForm when both are doing whole page refresh while posting data to the server and also seen lots of misleading answers, so by considering above requirement I decided to write this article. So let us see step by step .
 
Step 1: Create an MVC application.
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project" then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
  3. Choose MVC empty application option and click on OK

Step 2: Add model class.

Right click on Model folder in the created MVC application and add class named EmpModel and right the following lines of code as.

EmpModel.cs
  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace AjaxBeginFormwithMVC.Models  
  4. {  
  5.     public class EmpModel  
  6.     {  
  7.   
  8.         [Required]  
  9.         public string Name { getset; }  
  10.         [Required]  
  11.         public string City { getset; }  
  12.         [Required]  
  13.         public string Address { getset; }  
  14.     }  

Step 3: Add Home controller controller.

Right click on Controller folder in the created MVC application and add the controller class as:

Now after selecting controller template, click on add button then the following window appears,



Specify the controller name and click on add button, Now open the HomeController.cs file and write the following code into the Home controller class as:

HomeController.cs
  1. using AjaxBeginFormwithMVC.Models;  
  2. using System.Web.Mvc;  
  3.   
  4. namespace AjaxBeginFormwithMVC.Controllers  
  5. {  
  6.     public class HomeController : Controller  
  7.     {  
  8.         // GET: Home  
  9.         [HttpGet]  
  10.         public ActionResult EmployeeMaster()  
  11.         {  
  12.             return View();  
  13.         }  
  14.         [HttpPost]  
  15.         public ActionResult EmployeeMaster(EmpModel obj)  
  16.         {  
  17.             ViewBag.Records = "Name : " + obj.Name + " City:  " + obj.City + " Addreess: " + obj.Address;  
  18.             return PartialView("EmployeeMaster");  
  19.         }  
  20.     }  

In the above code, we have added EmployeeMaster Action result method and it returns the partial view named EmployeeMaster with input parameters value.

Step 4:
Add View,

Add strongly typed view named EmployeeMaster from EmpModel class: 
 
 

After clicking on add button the view generated .

Step 5:
Add Reference of jquery.unobtrusive-ajax

To work Ajax.BeginForm functionality properly we need to add the reference of jquery.unobtrusive-ajax library, there are many ways to add the reference of jQuery library into our project. The following are some methods,
  • Using NuGet package manager, you can install library and reference into the project.
Right click on created MVC project and find Nuget Package manager option, 

 
Now the following window will appear and search for the jQuery unobtrusive ajax as,

 

Choose appropriate version and click on Install button. It will install jQuery UI library to your project and library script file get added into the script folder of the created project which you can add reference into the project,
  • Use CDN library provided by Microsoft, jQuery, Google or any other which requires active internet connection.
  • Download library using NuGet and reference into the project.

The library will be look like as follows after adding it in script folder.

 
To work Ajax.BeginForm functionality properly don't forget to add the reference of the following jQuery library as,
  1. <script src="~/Scripts/jquery-1.10.2.js"></script>  
  2. <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script> 
After adding necessary code, files and logic the EmployeeMaster.cshtml code will look like the following,
  1. @model AjaxBeginFormwithMVC.Models.EmpModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "www.compilemode.com";  
  5. }  
  6. <script src="~/Scripts/jquery-1.10.2.js"></script>  
  7. <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>  
  8. <div id="divEmp">  
  9.   
  10.   
  11.     @using (Ajax.BeginForm("EmployeeMaster""Home"new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp" }))  
  12.     {  
  13.         @Html.AntiForgeryToken()  
  14.   
  15.         <div class="form-horizontal">  
  16.   
  17.             <hr />  
  18.             @Html.ValidationSummary(true""new { @class = "text-danger" })  
  19.             <div class="form-group">  
  20.                 @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  21.                 <div class="col-md-10">  
  22.                     @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  23.                     @Html.ValidationMessageFor(model => model.Name, ""new { @class = "text-danger" })  
  24.                 </div>  
  25.             </div>  
  26.   
  27.             <div class="form-group">  
  28.                 @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
  29.                 <div class="col-md-10">  
  30.                     @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })  
  31.                     @Html.ValidationMessageFor(model => model.City, ""new { @class = "text-danger" })  
  32.                 </div>  
  33.             </div>  
  34.   
  35.             <div class="form-group">  
  36.                 @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
  37.                 <div class="col-md-10">  
  38.                     @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
  39.                     @Html.ValidationMessageFor(model => model.Address, ""new { @class = "text-danger" })  
  40.                 </div>  
  41.             </div>  
  42.   
  43.             <div class="form-group">  
  44.                 <div class="col-md-offset-2 col-md-10">  
  45.                     <input type="submit" value="Save" class="btn btn-primary" />  
  46.                 </div>  
  47.             </div>  
  48.             <hr />  
  49.             <div class="form-group">  
  50.                 <div class="col-md-offset-2 col-md-12 text-success">  
  51.                    @ViewBag.Records  
  52.                 </div>  
  53.             </div>  
  54.   
  55.         </div>  
  56.     }  
  57. </div>  
  58. <script src="~/Scripts/jquery.validate.min.js"></script>  
  59. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> 
Now run the application and click on save button without entering text in textbox, it will fire the validation as in the following,
 
 
From preceding example it is clear that validation also get fired. Now enter the proper details and click on save button, it will pass data to the controller asynchronously without whole page refresh as,
 
 
From all the above examples, how to post data to controller without Page refresh in ASP.NET MVC using Ajax.BeginForm.

Note:
  • For the complete code, please download the sample zip file.
  • You need to use the jQuery library.
Summary

I hope this article is useful for all readers. If you have a suggestion then please contact me.

Up Next
    Ebook Download
    View all
    Learn
    View all