Post Strongly Typed Html.BeginForm View Data Into DataBase Using jQuery Ajax In ASP.NET MVC

Background

In many MVC projects you might have noticed while inserting data into the database using Html.BeginForm a whole post back occurs which consumes the server resources unnecessarily . So to avoid it , we will learn how to post the data of strongly typed view Html.BeginForm using jQuery Ajax post method in MVC which will insert the data asynchronously into the database without whole page post back.

In my previous article we have learned how to post data using Ajax.BeginForm without whole page postback but it has many limitation which few are listed below .
  1. Its works only for partial view .
  2. It will not be work with separate layout page.
  3. It requires extra jQuery library.

So in this article we will learn how to post whole data of strongly typed Html.BeginForm view into database without whole postback using jQuery json with the help of Ajax request instead of Ajax.BeginForm

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

Step 1: Create an MVC Application.

Now let us start with a step by step approach from the creation of a simple MVC application as in the following:

  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 OK. After clicking, the following window will appear:

  1. As shown in the preceding screenshot, click on Empty template and check MVC option, then click OK. This will create an empty MVC web application.
Step 2 : Add The Reference of Dapper ORM into Project.

Now next step is to add the reference of Dapper ORM into our created MVC Project. Here are the steps:
  1. Right click on Solution ,find Manage NuGet Package manager and click on it.
  2. After as shown into the image and type in search box "dapper".
  3. Select Dapper as shown into the image .
  4. Choose version of dapper library and click on install button.
 
 
After installing the Dapper library, it will be added into the References of our solution explorer of MVC application such as:



If wants to learn how to install correct Dapper library , watch my video tutorial using following link,
I hope you have followed the same steps and installed dapper library.

Step 3:
Create Model Class.

Now let's create the model class named EmpModel.cs by right clicking on model folder as in the following screenshot:
 
  
  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace PostStronglyTypedDataInMVC.Models  
  4. {  
  5.     public class EmpModel  
  6.     {  
  7.         [Required]  
  8.         public string Name { getset; }  
  9.         [Required]  
  10.         public string City { getset; }  
  11.         [Required]  
  12.         public string Address { getset; }  
  13.     }  

Note:

It is not mandatory that Model class should be in Model folder, it is just for better readability you can create this class anywhere in the solution explorer. This can be done by creating different folder name or without folder name or in a separate class library.

Step 4 : Create Controller.

Now let us add the MVC 5 controller as in the following screenshot:

 

After clicking on Add button it will show the window. specify the Controller name as Home with suffix Controller

Note:
The controller name must be having suffix as 'Controller' after specifying the name of controller.

Step 5 : Create Table and Stored procedure.

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 the employee details as in the following code snippet:

Now run the above script in sql editor it will generates the stored procedure to insert details into database .

Step 6: Create Repository class.

Now create Repository folder and Add EmpRepository.cs class for database related operations, Now create method in EmpRepository.cs to insert the data into database using stored procedure with the help of dapper as in the following code snippet:
  1. using Dapper;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Data.SqlClient;  
  5. using PostStronglyTypedDataInMVC.Models;  
  6.   
  7. namespace PostStronglyTypedDataInMVC.Repository  
  8. {  
  9.     public class EmpRepository  
  10.     {  
  11.         SqlConnection con;  
  12.         //To Handle connection related activities  
  13.         private void connection()  
  14.         {  
  15.             string constr = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();  
  16.             con = new SqlConnection(constr);  
  17.         }  
  18.         //Add employee details  
  19.         public void AddEmpDetails(EmpModel emp)  
  20.         {  
  21.            
  22.             DynamicParameters ObjParm = new DynamicParameters();  
  23.             ObjParm.Add("@Name", emp.Name);  
  24.             ObjParm.Add("@City", emp.City);  
  25.             ObjParm.Add("@Address", emp.Address);  
  26.             connection();  
  27.             con.Open();  
  28.             con.Execute("AddEmp", ObjParm,commandType:CommandType.StoredProcedure);  
  29.             con.Close();  
  30.             
  31.    
  32.         }  
  33.     }  

 Note
  1. In the above code we are manually opening and closing connection, however you can directly pass the connection string to the dapper without opening it. Dapper will automatically handle it.
Step 7: Create Method into the HomeController.cs file.

Now open the HomeController.cs and create the following action methods:
  1. using PostStronglyTypedDataInMVC.Models;  
  2. using System.Web.Mvc;  
  3. using PostStronglyTypedDataInMVC.Repository;  
  4. namespace PostStronglyTypedDataInMVC.Controllers  
  5. {  
  6.     public class HomeController : Controller  
  7.     {  
  8.         // GET: Home  
  9.         public ActionResult Employee()  
  10.         {  
  11.             return View();  
  12.         }  
  13.         [HttpPost]  
  14.         public JsonResult Employee(EmpModel obj)  
  15.         {  
  16.             EmpRepository ObjRepo = new EmpRepository();  
  17.             ObjRepo.AddEmpDetails(obj);  
  18.   
  19.             return Json("Success",JsonRequestBehavior.AllowGet);  
  20.         }  
  21.     }  

Step 8 : Creating strongly typed view named Employee using EmpModel class .

Right click on View folder of created application and choose add view , select EmpModel class and create scaffolding template as,



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

Step 9:
Create jQuery Post method

Now open the Employee.cshtml view and create the following jQuery Post method to call controller.
  1. <script type="text/javascript">  
  2.     $(document).ready(function () {  
  3.         $("#EmpForm").submit(function (e) {  
  4.             e.preventDefault();  
  5.             if ($(this).valid()) {  
  6.                 $.ajax({  
  7.                     type: "POST",  
  8.                     url: $(this).attr('action'),  
  9.                     data: $(this).serialize(),  
  10.                     success: function (res)  
  11.                     {  
  12.                         alert("Records added Successfully.");  
  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>     
Now after adding the required api or jQuery reference and code the entire Employee.cshtml view will be look like as follows Employee.cshtml,
  1. @model PostStronglyTypedDataInMVC.Models.EmpModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "www.compilemode.com";  
  5. }  
  6. <script src="~/Scripts/jquery-2.2.3.min.js"></script>  
  7. <script src="~/Scripts/jquery.validate.min.js"></script>  
  8. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  
  9. <script type="text/javascript">  
  10.     $(document).ready(function () {  
  11.         $("#EmpForm").submit(function (e) {  
  12.             e.preventDefault();  
  13.             if ($(this).valid()) {  
  14.                 $.ajax({  
  15.                     type: "POST",  
  16.                     url: $(this).attr('action'),  
  17.                     data: $(this).serialize(),  
  18.                     success: function (res)  
  19.                     {  
  20.                         alert("Records added Successfully.");  
  21.                     }  
  22.                 });  
  23.             }  
  24.         });  
  25.         
  26.     })  
  27.   
  28. </script>  
  29.   
  30. @using (Html.BeginForm("Employee","Home",FormMethod.Post,new {id="EmpForm" }))  
  31. {  
  32.     @Html.AntiForgeryToken()  
  33.       
  34.     <div class="form-horizontal">  
  35.          
  36.         <hr />  
  37.         @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
  38.         <div class="form-group">  
  39.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  40.             <div class="col-md-10">  
  41.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  42.                 @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })  
  43.             </div>  
  44.         </div>  
  45.   
  46.         <div class="form-group">  
  47.             @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
  48.             <div class="col-md-10">  
  49.                 @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })  
  50.                 @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })  
  51.             </div>  
  52.         </div>  
  53.   
  54.         <div class="form-group">  
  55.             @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
  56.             <div class="col-md-10">  
  57.                 @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
  58.                 @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })  
  59.             </div>  
  60.         </div>  
  61.   
  62.         <div class="form-group">  
  63.             <div class="col-md-offset-2 col-md-10">  
  64.                 <input type="submit" value="Save" class="btn btn-primary" />  
  65.             </div>  
  66.         </div>  
  67.         <hr />  
  68.         
  69.   
  70.     </div>  

After adding model, view , controller and Repository folder our final solution explorer will be look like as follows,
 
 

Now we have done all coding to upload files.

Step 10 : Now run the application.

After running the application initial screen will be look like as follows,
 
 
Now click on Add save button without entering the details then the following error message shows which we have defined in model class as,

 
Now enter the proper details as,
 
 
Now click on save button, It will shows the following message after successfully inserting data into database as,
 


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 have learned how to post strongly typed Html.BeginForm view data Into Database using jQuery Ajax In ASP.NET MVC.

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

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

Read more articles on ASP.NET:

Up Next
    Ebook Download
    View all
    Learn
    View all