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.
- Create Procedure [dbo].[InsertData]
- (
- @FName varchar(50),
- @Lname Varchar(50),
- @Compnay varchar(50)
-
- )
- as
- begin
-
- INSERT INTO [dbo].[Employee]
- ([FirstName]
- ,[LastName]
- ,[Company])
- VALUES
- (
- @FName,
- @Lname,
- @Compnay
- )
- End
Step 2 Create Web Application
Now Let us create the sample web application as follows:
- "Start" -> "All Programs" -> "Microsoft Visual Studio 2010".
- "File" -> "New Project" -> "C#" -> "Empty Project" (to avoid adding a master page).
- Provide the website a name such as "InsertingFormDataUsingWebAPI" or another as you wish and specify the location.
- Then right-click on the Solution Explorer -> "Add New Item" -> Add Web Form.
- 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.
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="InsertingFormDataUsingWebAPI.Default" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <html xmlns="https://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title>Article by Vithal Wadje</title>
-
- </head>
- <body style="background-color:Navy;color:White">
- <form id="form1" runat="server">
- <br /><br />
- <table>
- <tr>
- <td>
- First Name
- </td>
- <td>
- <asp:TextBox runat="server" ID="txtFirstName" />
- </td>
- </tr>
- <tr>
- <td>
- Last Name
- </td>
- <td>
- <asp:TextBox runat="server" ID="txtLastName" />
- </td>
- </tr>
- <tr>
- <td>
- Company
- </td>
- <td>
- <asp:TextBox runat="server" ID="txtCompany" />
- </td>
- </tr>
- <tr>
- <td>
- </td>
- <td>
- <asp:Button Text="Save" runat="server" ID="btnSave" />
- </td>
- </tr>
- </table>
- <br />
-
- </form>
- </body>
- </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:
- public class Employee
- {
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string Company { get; set; }
-
- }
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:
Step 5 Create Repository Class
Now add the following method into the Repository Class named AddEmployee that does all the data access related activities:
- public string AddEmployees(Employee Emp)
- {
- connection();
- com = new SqlCommand("InsertData", con);
- com.CommandType = CommandType.StoredProcedure;
- com.Parameters.AddWithValue("@FName", Emp.FirstName);
- com.Parameters.AddWithValue("@Lname", Emp.LastName);
- com.Parameters.AddWithValue("@Compnay", Emp.Company);
- con.Open();
- int i = com.ExecuteNonQuery();
- con.Close();
- if (i >= 1)
- {
- return "New Employee Added Successfully";
-
- }
- else
- {
- return "Employee Not Added";
-
- }
- }
The entire EmpRepository class file will be as follows,
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Data.SqlClient;
- using System.Configuration;
- using System.Data;
-
- namespace InsertingFormDataUsingWebAPI
- {
- public class EmpRepository
- {
-
- private SqlConnection con;
- private SqlCommand com;
-
- private void connection()
- {
- string constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();
- con = new SqlConnection(constr);
-
-
- }
-
- public string AddEmployees(Employee Emp)
- {
- connection();
- com = new SqlCommand("InsertData", con);
- com.CommandType = CommandType.StoredProcedure;
- com.Parameters.AddWithValue("@FName", Emp.FirstName);
- com.Parameters.AddWithValue("@Lname", Emp.LastName);
- com.Parameters.AddWithValue("@Compnay", Emp.Company);
- con.Open();
- int i = com.ExecuteNonQuery();
- con.Close();
- if (i >= 1)
- {
- return "New Employee Added Successfully";
-
- }
- else
- {
- return "Employee Not Added";
-
- }
- }
- }
- }
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,
- public class EmpController : ApiController
- {
-
-
- static EmpRepository repository = new EmpRepository();
-
-
- public string AddEmployees(Employee Emp)
- {
-
- var response = repository.AddEmployees(Emp);
- return response;
- }
-
- }
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:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
-
- namespace InsertingFormDataUsingWebAPI
- {
- public class EmpController : ApiController
- {
-
-
- static EmpRepository repository = new EmpRepository();
-
-
- public string AddEmployees(Employee Emp)
- {
-
- var response = repository.AddEmployees(Emp);
- return response;
-
- }
-
- }
- }
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,
- public static void Register(HttpConfiguration config)
- {
-
-
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
-
- }
The entire WebApiConfig.cs will be as follows,
- using System.Web.Http;
-
- namespace InsertingFormDataUsingWebAPI
- {
- public class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
-
-
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
-
- }
- }
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,
- protected void Application_Start(object sender, EventArgs e)
- {
- WebApiConfig.Register(GlobalConfiguration.Configuration);
-
- }
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,
- function AddEmp() {
-
- var Emp = {};
- Emp.FirstName = $("#txtFirstName").val();
- Emp.LastName = $("#txtLastName").val();
- Emp.Company = $("#txtCompany").val();
-
-
- $.ajax({
- url:"<%=Page.ResolveUrl("/api/Emp/AddEmployees")%>",
- type: "POST",
- contentType: "application/json;charset=utf-8",
- data: JSON.stringify(Emp),
- dataType: "json",
- success: function (response) {
-
- alert(response);
-
- },
-
- error: function (x, e) {
- alert('Failed');
- alert(x.responseText);
- alert(x.status);
-
- }
- });
-
- }
-
- $(document).ready(function ()
- {
-
- $("#btnSave").click(function (e) {
-
- AddEmp();
- e.preventDefault();
-
- });
-
- });
Now the entire default.aspx page will be as follows,
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="InsertingFormDataUsingWebAPI.Default" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <html xmlns="https://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title>Article by Vithal Wadje</title>
- <script src="jquery-1.7.1.js" type="text/javascript"></script>
-
- <script type="text/javascript">
-
-
- function AddEmp() {
-
- var Emp = {};
- Emp.FirstName = $("#txtFirstName").val();
- Emp.LastName = $("#txtLastName").val();
- Emp.Company = $("#txtCompany").val();
-
-
- $.ajax({
- url:"<%=Page.ResolveUrl("/api/Emp/AddEmployees")%>",
- type: "POST",
- contentType: "application/json;charset=utf-8",
- data: JSON.stringify(Emp),
- dataType: "json",
- success: function (response) {
-
- alert(response);
-
- },
-
- error: function (x, e) {
- alert('Failed');
- alert(x.responseText);
- alert(x.status);
-
- }
- });
- }
-
- $(document).ready(function ()
- {
- $("#btnSave").click(function (e) {
-
- AddEmp();
- e.preventDefault();
- });
- });
-
- </script>
- </head>
- <body style="background-color:Navy;color:White">
- <form id="form1" runat="server">
- <br /><br />
- <table>
- <tr>
- <td>
- First Name
- </td>
- <td>
- <asp:TextBox runat="server" ID="txtFirstName" />
- </td>
- </tr>
- <tr>
- <td>
- Last Name
- </td>
- <td>
- <asp:TextBox runat="server" ID="txtLastName" />
- </td>
- </tr>
- <tr>
- <td>
- Company
- </td>
- <td>
- <asp:TextBox runat="server" ID="txtCompany" />
- </td>
- </tr>
- <tr>
- <td>
- </td>
- <td>
- <asp:Button Text="Save" runat="server" ID="btnSave" />
- </td>
- </tr>
- </table>
- <br />
-
- </form>
- </body>
- </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,
Now run the application.
Now enter some records into the preceding fields and click on the Save button. The following message will be shown.
Now let us see into the database table, the added records will be shown as follows,
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.