Inserting ASP.NET Form Data Into Database Using Web API

Background

I have often read the common question in forum posts of how to insert the ASP.Net form data using the Web API into a database. But no one has provided the proper solution. So based on the preceding requirement, I have decided to write this article. Let us start creating an application so beginners can also understand.
 
Step 1 Create Table and Stored Procedure
 
First create the table named Employee using the following script:
  1. CREATE TABLE [dbo].[Employee](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [FirstName] [varchar](50) NULL,  
  4.     [LastName] [varchar](50) NULL,  
  5.     [Company] [varchar](50) NULL,  
  6.  CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
  7. (  
  8.     [Id] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  10. ON [PRIMARY
 The design view of the table will look as follows:
 
ASP.NET
 
Now create a Stored Procedure to insert the data as:
  1. Create Procedure [dbo].[InsertData]  
  2. (  
  3. @FName varchar(50),  
  4. @Lname Varchar(50),  
  5. @Compnay varchar(50)  
  6.   
  7. )  
  8. as  
  9. begin  
  10.   
  11. INSERT INTO [dbo].[Employee]  
  12.            ([FirstName]  
  13.            ,[LastName]  
  14.            ,[Company])  
  15.      VALUES  
  16.            (  
  17.            @FName,  
  18.            @Lname,  
  19.            @Compnay  
  20.           )  
  21. End 
Step 2 Create Web Application
 
Now Let us create the sample web application as follows:
  1. "Start" -> "All Programs" -> "Microsoft Visual Studio 2010".

  2. "File" -> "New Project" -> "C#" -> "Empty Project" (to avoid adding a master page).

  3. Provide the website a name such as "InsertingFormDataUsingWebAPI" or another as you wish and specify the location.

  4. Then right-click on the Solution Explorer -> "Add New Item" -> Add Web Form.

  5. Drag and drop three text boxes and one Button onto the <form> section of the Default.aspx page.

Now the default.aspx page source code will be as follows.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="InsertingFormDataUsingWebAPI.Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head id="Head1" runat="server">  
  7.     <title>Article  by Vithal Wadje</title>  
  8.      
  9. </head>  
  10. <body style="background-color:Navy;color:White">  
  11.     <form id="form1" runat="server">  
  12.     <br /><br />  
  13.     <table>  
  14.         <tr>  
  15.             <td>  
  16.                 First Name  
  17.             </td>  
  18.             <td>  
  19.                 <asp:TextBox runat="server" ID="txtFirstName" />  
  20.             </td>  
  21.         </tr>  
  22.         <tr>  
  23.             <td>  
  24.                 Last Name  
  25.             </td>  
  26.             <td>  
  27.                 <asp:TextBox runat="server" ID="txtLastName" />  
  28.             </td>  
  29.         </tr>  
  30.         <tr>  
  31.             <td>  
  32.                 Company  
  33.             </td>  
  34.             <td>  
  35.                 <asp:TextBox runat="server" ID="txtCompany" />  
  36.             </td>  
  37.         </tr>  
  38.         <tr>  
  39.             <td>  
  40.             </td>  
  41.             <td>  
  42.                 <asp:Button Text="Save" runat="server" ID="btnSave" />  
  43.             </td>  
  44.         </tr>  
  45.     </table>  
  46.     <br />  
  47.       
  48.     </form>  
  49. </body>  
  50. </html> 
Step 3 Create Property Class
 
We have a .aspx Web form to insert the records. Now create the Property class Named Employee class as in the following:
  1. public class Employee   
  2. {  
  3.    public string FirstName { getset; }  
  4.    public string LastName { getset; }  
  5.    public string Company { getset; }  
  6.   

Step 4 Add Web API Controller Class
 
We created the preceding properties as in our table structure to insert the preceding employee details into the database. Now let us add a web API controller class into the web application by right-clicking on the project in the Solution Explorer and rename it to EmpController with controller suffix  as:
 
ASP.NET
 
Step 5 Create Repository Class
 
Now add the following method into the Repository Class named AddEmployee that does all the data access related activities:
  1. public string AddEmployees(Employee Emp)    
  2. {    
  3.     connection();    
  4.     com = new SqlCommand("InsertData", con);    
  5.     com.CommandType = CommandType.StoredProcedure;    
  6.     com.Parameters.AddWithValue("@FName", Emp.FirstName);    
  7.     com.Parameters.AddWithValue("@Lname", Emp.LastName);    
  8.     com.Parameters.AddWithValue("@Compnay", Emp.Company);    
  9.     con.Open();    
  10.     int i = com.ExecuteNonQuery();    
  11.     con.Close();    
  12.     if (i >= 1)    
  13.     {    
  14.         return "New Employee Added Successfully";    
  15.   
  16.     }    
  17.     else    
  18.     {    
  19.         return "Employee Not Added";    
  20.   
  21.     }    
  22. }  
The entire EmpRepository class file will be as follows,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Data.SqlClient;  
  6. using System.Configuration;  
  7. using System.Data;  
  8.   
  9. namespace InsertingFormDataUsingWebAPI  
  10. {  
  11.     public class EmpRepository  
  12.     {  
  13.   
  14.         private SqlConnection con;  
  15.         private SqlCommand com;  
  16.         
  17.         private void connection()  
  18.         {  
  19.             string constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();  
  20.             con = new SqlConnection(constr);  
  21.   
  22.   
  23.         }  
  24.   
  25.         public string AddEmployees(Employee Emp)  
  26.         {  
  27.             connection();  
  28.             com = new SqlCommand("InsertData", con);  
  29.             com.CommandType = CommandType.StoredProcedure;  
  30.             com.Parameters.AddWithValue("@FName", Emp.FirstName);  
  31.             com.Parameters.AddWithValue("@Lname", Emp.LastName);  
  32.             com.Parameters.AddWithValue("@Compnay", Emp.Company);  
  33.             con.Open();  
  34.             int i = com.ExecuteNonQuery();  
  35.             con.Close();  
  36.             if (i >= 1)  
  37.             {  
  38.                 return "New Employee Added Successfully";  
  39.   
  40.             }  
  41.             else  
  42.             {  
  43.                 return "Employee Not Added";  
  44.   
  45.             }  
  46.         }  
  47.     }  

Step 6 Create Post method
 
Create a Post method in the ASP.Net Web API Controller Class.
 
Open the EmpController class that we created, delete the existing methods and create the AddEmployees Method and call the EmpRepository class method as in the following,
  1. public class EmpController : ApiController  
  2. {  
  3.   
  4.     //creating the object of EmpRepository class  
  5.     static EmpRepository repository = new EmpRepository();  
  6.   
  7.   
  8.     public string AddEmployees(Employee Emp)  
  9.     {  
  10.         //calling EmpRepository Class Method and storing Repsonse   
  11.         var response = repository.AddEmployees(Emp);  
  12.         return response;  

  13.     }  
  14.   

You have seen that the preceding EmpController class is inherited from the ApiController class and we have created the method AddEmployee that the calls EmpRepository class method named AddEmployees. The entire EmpController class will be as follows:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7.   
  8. namespace InsertingFormDataUsingWebAPI  
  9. {  
  10.     public class EmpController : ApiController  
  11.     {  
  12.   
  13.         //creating the object of EmpRepository class  
  14.         static EmpRepository repository = new EmpRepository();  
  15.   
  16.   
  17.         public string AddEmployees(Employee Emp)  
  18.         {  
  19.             //calling EmpRepository Class Method and storing Repsonse   
  20.             var response = repository.AddEmployees(Emp);  
  21.             return response;  
  22.   
  23.         }  
  24.   
  25.     }  

Step 7 Configure  ASP.Net Web API routing
 
We need to configure the routing for incoming requests. Let us create WebApiConfig.cs by right-clicking on the project in the Solution Explorer and create the following method as in the following,
  1. public static void Register(HttpConfiguration config)  
  2.        {  
  3.   
  4.   
  5.            config.Routes.MapHttpRoute(  
  6.                name: "DefaultApi",  
  7.                routeTemplate: "api/{controller}/{id}",  
  8.                defaults: new { id = RouteParameter.Optional }  
  9.            );  
  10.  
  11.        } 
The entire WebApiConfig.cs will be as follows,
  1. using System.Web.Http;  
  2.   
  3. namespace InsertingFormDataUsingWebAPI  
  4. {  
  5.     public class WebApiConfig  
  6.     {  
  7.         public static void Register(HttpConfiguration config)  
  8.         {  
  9.   
  10.   
  11.             config.Routes.MapHttpRoute(  
  12.                 name: "DefaultApi",  
  13.                 routeTemplate: "api/{controller}/{id}",  
  14.                 defaults: new { id = RouteParameter.Optional }  
  15.             ); 
  16.        }  
  17.   
  18.     }  

Step 8 Call the Register method
 
Call the Register method from the Global.asax file.
 
Add the Global.asax file to the ASP.Net web application if not already present and call the Register method on Application_Start Event as in the following,
  1. protected void Application_Start(object sender, EventArgs e)  
  2. {  
  3.      WebApiConfig.Register(GlobalConfiguration.Configuration);  
  4.          

Step 9 Call ASP.Net Web API Controller method
 
Call the ASP.Net Web API Controller method from the .aspx page using JSON.
 
Now we need to call the Web API controller method from the .aspx page. To do this we need to create a JSON method using jQuery as in the following,
  1. function AddEmp() {  
  2.          
  3.    var Emp = {};  
  4.    Emp.FirstName = $("#txtFirstName").val();  
  5.    Emp.LastName = $("#txtLastName").val();           
  6.    Emp.Company = $("#txtCompany").val();    
  7.   
  8.  
  9.    $.ajax({  
  10.       url:"<%=Page.ResolveUrl("/api/Emp/AddEmployees")%>",   
  11.       type: "POST",  
  12.       contentType: "application/json;charset=utf-8",  
  13.       data: JSON.stringify(Emp),  
  14.       dataType: "json",  
  15.       success: function (response) {  
  16.   
  17.         alert(response);  
  18.                        
  19.      },  
  20.   
  21.      error: function (x, e) {  
  22.          alert('Failed');  
  23.          alert(x.responseText);  
  24.          alert(x.status);  
  25.   
  26.      }  
  27.   });  
  28.     
  29. }       
  30.     
  31. $(document).ready(function ()  
  32. {  
  33.   
  34.     $("#btnSave").click(function (e) {  
  35.               
  36.        AddEmp();  
  37.        e.preventDefault();  
  38.   
  39.     });  
  40.   
  41. }); 
Now the entire default.aspx page will be as follows,
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="InsertingFormDataUsingWebAPI.Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head id="Head1" runat="server">  
  7.     <title>Article  by Vithal Wadje</title>  
  8.     <script src="jquery-1.7.1.js" type="text/javascript"></script>  
  9.       
  10.     <script type="text/javascript">  
  11.   
  12.          
  13.         function AddEmp() {  
  14.             
  15.             var Emp = {};  
  16.             Emp.FirstName = $("#txtFirstName").val();  
  17.             Emp.LastName = $("#txtLastName").val();           
  18.             Emp.Company = $("#txtCompany").val();    
  19.   
  20.   
  21.             $.ajax({  
  22.                 url:"<%=Page.ResolveUrl("/api/Emp/AddEmployees")%>",   
  23.                 type: "POST",  
  24.                 contentType: "application/json;charset=utf-8",  
  25.                 data: JSON.stringify(Emp),  
  26.                 dataType: "json",  
  27.                 success: function (response) {  
  28.   
  29.                     alert(response);           
  30.   
  31.                 },  
  32.   
  33.                 error: function (x, e) {  
  34.                     alert('Failed');  
  35.                     alert(x.responseText);  
  36.                     alert(x.status);  
  37.   
  38.                 }  
  39.             });   
  40.         }       
  41.   
  42.         $(document).ready(function ()  
  43.          {   
  44.             $("#btnSave").click(function (e) {               
  45.   
  46.                 AddEmp();  
  47.                 e.preventDefault();  
  48.             });    
  49.         });  
  50.   
  51.     </script>  
  52. </head>  
  53. <body style="background-color:Navy;color:White">  
  54.     <form id="form1" runat="server">  
  55.     <br /><br />  
  56.     <table>  
  57.         <tr>  
  58.             <td>  
  59.                 First Name  
  60.             </td>  
  61.             <td>  
  62.                 <asp:TextBox runat="server" ID="txtFirstName" />  
  63.             </td>  
  64.         </tr>  
  65.         <tr>  
  66.             <td>  
  67.                 Last Name  
  68.             </td>  
  69.             <td>  
  70.                 <asp:TextBox runat="server" ID="txtLastName" />  
  71.             </td>  
  72.         </tr>  
  73.         <tr>  
  74.             <td>  
  75.                 Company  
  76.             </td>  
  77.             <td>  
  78.                 <asp:TextBox runat="server" ID="txtCompany" />  
  79.             </td>  
  80.         </tr>  
  81.         <tr>  
  82.             <td>  
  83.             </td>  
  84.             <td>  
  85.                 <asp:Button Text="Save" runat="server" ID="btnSave" />  
  86.             </td>  
  87.         </tr>  
  88.     </table>  
  89.     <br />  
  90.       
  91.     </form>  
  92. </body>  
  93. </html> 
Also we need to add a jQuery library reference so don't forget it to add it. Now the entire Solution Explorer will look as follows,
 
ASP.NET

Now run the application.
 
ASP.NET
 
Now enter some records into the preceding fields and click on the Save button. The following message will be shown.
 
ASP.NET
 
Now let us see into the database table, the added records will be shown as follows,
 
ASP.NET

Now you have seen how the records are inserted into the database using the ASP.Net Web API with Web Forms.

Notes
  • For detailed code please download the sample Zip file.

  • Do a proper validation such as date input values when implementing.

  • Make the changes in the web.config file depending on your server details for the connection string.
Summary

You have learned here how to insert records into the database using the ASP.Net Web API with Web Forms. I hope this article is useful for all readers. If you have a suggestion then please contact me.

Next Recommended Readings