Step 1 : Create Table and Stored Procedure
First create the table named Employee using the following script:
CREATE TABLE [dbo].[Employee]( [Id] [int] IDENTITY(1,1) NOT NULL, [FirstName] [varchar](50) NULL, [LastName] [varchar](50) NULL, [Company] [varchar](50) NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
Now create a Stored Procedure to insert the data as:
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.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="InsertingFormDataUsingWebAPI.Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://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
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
Step 5: Create Repository Class
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
public class EmpController : ApiController { //creating the object of EmpRepository class static EmpRepository repository = new EmpRepository(); public string AddEmployees(Employee Emp) { //calling EmpRepository Class Method and storing Repsonse 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 { //creating the object of EmpRepository class static EmpRepository repository = new EmpRepository(); public string AddEmployees(Employee Emp) { //calling EmpRepository Class Method and storing Repsonse var response = repository.AddEmployees(Emp); return response; } } }
Step 7: Configure ASP.Net Web API routing
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
protected void Application_Start(object sender, EventArgs e) { WebApiConfig.Register(GlobalConfiguration.Configuration); }
Step 9: Call ASP.Net Web API Controller method
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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://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>
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 sample file i will upload soon.
- 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
Post a Comment