I have often read the common question in forum posts as how to
insert the ASP.Net form data into a database and display it using the
Web API. So based on the this requirement, I have decided to write this
article. Let us start creating an application so beginners can also
understand.
Now add the following method into the Repository Class named AddEmployee and GetAllEmp that does all the data access related activities:
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
Step 3 : Create Property Class
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 "DisplayingFormDataUsingWebAPI" 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>
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 EmpController with
controller suffix.
Step 5: Create Repository Class to add and view records
public IEnumerable<Employee> GetAllEmp() { connection(); com = new SqlCommand("select *from Employee", con); com.CommandType = CommandType.Text; SqlDataAdapter da = new SqlDataAdapter(com); DataTable dt = new DataTable(); con.Open(); da.Fill(dt); con.Close(); foreach (DataRow row in dt.Rows) { yield return new Employee { Id = Convert.ToInt32(row["Id"]), FirstName = Convert.ToString(row["FirstName"]), LastName = Convert.ToString(row["LastName"]), Company = Convert.ToString(row["Company"]), }; } } 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 DisplayingFormDataUsingWebAPI { public class EmpRepository { private SqlConnection con; private SqlCommand com; private void connection() { string constr = ConfigurationManager.ConnectionStrings["getconn"].ToString(); con = new SqlConnection(constr); } public IEnumerable<Employee> GetAllEmp() { connection(); com = new SqlCommand("select *from Employee", con); com.CommandType = CommandType.Text; SqlDataAdapter da = new SqlDataAdapter(com); DataTable dt = new DataTable(); con.Open(); da.Fill(dt); con.Close(); foreach (DataRow row in dt.Rows) { yield return new Employee { Id = Convert.ToInt32(row["Id"]), FirstName = Convert.ToString(row["FirstName"]), LastName = Convert.ToString(row["LastName"]), Company = Convert.ToString(row["Company"]), }; } } 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 and Get method
Create a Post and Get method in the ASP.Net Web API Controller Class.
Open the EmpController class that we created, delete the existing
methods and create the AddEmployees and GetAllEmp method and call the
EmpRepository class method as in the following:
//creating the object of EmpRepository class static EmpRepository repository = new EmpRepository(); public IEnumerable<Employee> GetAllEmp() { var users = repository.GetAllEmp(); return users; } 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
calls the 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 DisplayingFormDataUsingWebAPI { public class EmpController : ApiController { //creating the object of EmpRepository class static EmpRepository repository = new EmpRepository(); public IEnumerable<Employee> GetAllEmp() { var users = repository.GetAllEmp(); return users; } public string AddEmployees(Employee Emp) { //calling EmpRepository Class Method and storing Repsonse var response = repository.AddEmployees(Emp); return response; } } }
Step 7: 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:
<script type="text/javascript"> function GetAllEmp() { $.getJSON("api/Emp", function (data) { $('#bindemp').empty(); $.each(data, function (key, val) { var row = "<tr><td>" + val.Id + "</td> <td></td> <td>" + val.FirstName + " " + val.LastName + "</td> <td></td> <td>" + val.Company + "</td></tr>"; $(row).appendTo($('#bindemp')); }); }); } 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); GetAllEmp(); }, error: function (x, e) { alert('Failed'); alert(x.responseText); alert(x.status); } }); } $(document).ready(function () { GetAllEmp(); $("#btnSave").click(function (e) { AddEmp(); e.preventDefault(); }); }); </script>
Now the entire default.aspx page will be as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DisplayingFormDataUsingWebAPI.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 GetAllEmp() { $.getJSON("api/Emp", function (data) { $('#bindemp').empty(); $.each(data, function (key, val) { var row = "<tr><td>" + val.Id + "</td> <td></td> <td>" + val.FirstName + " " + val.LastName + "</td> <td></td> <td>" + val.Company + "</td></tr>"; $(row).appendTo($('#bindemp')); }); }); } 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); GetAllEmp(); }, error: function (x, e) { alert('Failed'); alert(x.responseText); alert(x.status); } }); } $(document).ready(function () { GetAllEmp(); $("#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 /> <table> <thead> <tr> <td> Id </td> <td></td> <td> Name </td> <td></td> <td> Company </td> </tr> </thead> <tbody id="bindemp"> </tbody> </table> </form> </body> </html>
Now run the application, the UI will be as follows:
Now enter some records into the preceding fields and click on the
Save button. Then the following screen shows the added records.
Now add another record.
Now you have seen how the insertion of records into the database and display it using Web API with Web Forms works.
Notes
Notes
- 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 and
display it 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.
Post a Comment