Inserting Data Using jQuery Ajax POST Method In ASP.NET MVC 5

Background

In many MVC projects and other applications you might have noticed while inserting data into the database whole post back occurs which consumes the server resources unnecessarily and some time inserts the duplicate records when page is post back again. So to avoid it we will learn how to post the data using jQuery Ajax post method in MVC which will insert the data asynchronously into the database without whole page postback.

You might be interested in one of my ASP.NET article Inserting Form Data Into Database Using Stored Procedure In ASP.NET C# posted in December 2012 with 149 k+ views and based on the same I  decided same functionality article using ASP.NET MVC.

So let's demonstrate it by using a simple MVC application.

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: Create Model Class.

Right click on Model folder in the created MVC application, give the class name employee or as you wish and click OK.

EmpModel.cs
  1. public class EmpModel  
  2. {  
  3.     public string Name { getset; }  
  4.     public string City { getset; }  
  5.     public string Address { getset; }  
  6.          

Step 3: Create Table and Stored procedures.

Now before creating the views let us create the table named Employee in the database according to our model fields to store the details:



Create stored procedure to insert records
  1. Create procedure [dbo].[AddEmp]    
  2. (    
  3.    @Name varchar (50),    
  4.    @City varchar (50),    
  5.    @Address varchar (50)    
  6. )    
  7. as    
  8. begin    
  9.    Insert into Employee values(@Name,@City,@Address)    
  10. End   
I hope you have created the same table structure as shown above. Now create the stored procedures to insert, update, view and delete the details as in the following code snippet:

Step 4: Add controller class.

Right click on Controller folder in the created MVC application; give the class name. I have given class name Home and clicked OK.

HomeControlle.cs
  1. public class HomeController : Controller    
  2. {    
  3.     private SqlConnection con;    
  4.        
  5.     // GET: AddEmployee  
  6.     public ActionResult AddEmployee()    
  7.     {    
  8.            
  9.         return View();    
  10.     }    
  11.     //Post method to add details    
  12.     [HttpPost]    
  13.     public ActionResult AddEmployee(EmpModel obj)    
  14.     {    
  15.         AddDetails(obj);    
  16.   
  17.         return View();    
  18.     }    
  19.   
  20.     //To Handle connection related activities    
  21.     private void connection()    
  22.     {    
  23.         string constr = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();    
  24.         con = new SqlConnection(constr);    
  25.   
  26.     }    
  27.     //To add Records into database     
  28.     private void AddDetails(EmpModel obj)    
  29.     {    
  30.         connection();    
  31.         SqlCommand com = new SqlCommand("AddEmp", con);    
  32.         com.CommandType = CommandType.StoredProcedure;    
  33.         com.Parameters.AddWithValue("@Name", obj.Name);    
  34.         com.Parameters.AddWithValue("@City", obj.City);    
  35.         com.Parameters.AddWithValue("@Address", obj.Address);    
  36.         con.Open();    
  37.         com.ExecuteNonQuery();    
  38.         con.Close();    
  39.   
  40.     }    
  41. }  
Step 5: Add View

Right click on View folder of created MVC application project and add empty view named AddEmployee.cshtml.

Step 6:
Create jQuery Post method

Now open the AddEmployee.cshtml view and create the following jQuery Post method to call controller.
  1. <script>  
  2.     $(document).ready(function () { 
  3. //function will be called on button click having id btnsave
  4.         $("#btnSave").click(function () { 
  5.             $.ajax(  
  6.             {  
  7.                 type: "POST"//HTTP POST Method  
  8.                 url: "Home/AddEmployee"// Controller/View   
  9.                 data: { //Passing data  
  10.                     Name: $("#txtName").val(), //Reading text box values using Jquery   
  11.                     City: $("#txtAddress").val(),  
  12.                     Address: $("#txtcity").val()  
  13.                 }  
  14.   
  15.             });  
  16.   
  17.         });  
  18.     });  
  19.   
  20. </script> 
Note
  • To work with jQuery we need to reference jQuery library. You can use the following CDN jQuery library from any provider such as Microsoft, Google or jQuery.
  1. https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js 
To use above jQuery library you need an active internet connection, if you don't have then you can use the following offline jQuery library as well:
  1. <script src="~/Scripts/jquery-1.10.2.min.js"></script>   
Step 7: Add controls on the Razor view.

Now after adding the library and form controls, the AddEmployee.cshtml code will look like as:
  1. @{  
  2.     ViewBag.Title = "www.compilemode.com";  
  3. }  
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
  5. <script>  
  6.     $(document).ready(function () {  
  7.         $("#btnSave").click(function () {  
  8.             $.ajax(  
  9.             {  
  10.                 type: "POST", //HTTP POST Method  
  11.                 url: "Home/AddEmployee", // Controller/View   
  12.                 data: { //Passing data  
  13.                     Name: $("#txtName").val(), //Reading text box values using Jquery   
  14.                     City: $("#txtAddress").val(),  
  15.                     Address: $("#txtcity").val()  
  16.                 }  
  17.   
  18.             });  
  19.   
  20.         });  
  21.     });  
  22.   
  23. </script>  
  24. <br /><br />  
  25. <fieldset>  
  26.     <div class="form-horizontal">  
  27.         <div class="editor-label">  
  28.             Name  
  29.         </div>  
  30.         <div class="editor-label">  
  31.             <input type="text" id="txtName" />  
  32.         </div>  
  33.   
  34.         <div class="editor-label">  
  35.             Address  
  36.         </div>  
  37.         <div class="editor-label">  
  38.             <input type="text" id="txtAddress" />  
  39.         </div>  
  40.   
  41.         <div class="editor-label">  
  42.             City  
  43.         </div>  
  44.         <div class="editor-label">  
  45.             <input type="text" id="txtcity" />  
  46.         </div>  
  47.         <div class="editor-label">  
  48.             <br />  
  49.             <input class="btn-default" type="button" id="btnSave" value="Save" />  
  50.         </div>  
  51.     </div>  
  52. </fieldset> 
Now everything is ready, run the application and enter the details into the following form.



After entering the details click on save button. The details will get added into the database as in the following:



From all the above examples we learned how to insert data using jQuery post method without whole page postback.

Note
  • Do a proper validation such as date input values when implementing.
  • Download the Zip file of the sample application for a better understanding.
  • Make the changes in the web.config file depending on your server details for the connection string.
Summary

From all the preceding examples you have learned how to insert data using jQuery post method. I hope this article is useful for all readers, if you have a suggestion then please contact me.


Similar Articles