Displaying Data on ASP.Net Web Form Using Web API

Background

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.
 
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]  
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 "DisplayingFormDataUsingWebAPI" 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.     
  7. }   
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
 
Now add the following method into the Repository Class named AddEmployee and GetAllEmp that does all the data access related activities: 
  1. public IEnumerable<Employee> GetAllEmp()  
  2.      {  
  3.          connection();  
  4.    
  5.        com = new SqlCommand("select *from Employee", con);  
  6.        com.CommandType = CommandType.Text;  
  7.          SqlDataAdapter da = new SqlDataAdapter(com);  
  8.          DataTable dt = new DataTable();  
  9.          con.Open();  
  10.          da.Fill(dt);  
  11.          con.Close();  
  12.   
  13.          foreach (DataRow row in dt.Rows)  
  14.          {  
  15.              yield return new Employee  
  16.              {  
  17.                  Id = Convert.ToInt32(row["Id"]),  
  18.                  FirstName = Convert.ToString(row["FirstName"]),  
  19.                  LastName = Convert.ToString(row["LastName"]),  
  20.                  Company = Convert.ToString(row["Company"]),  
  21.   
  22.              };  
  23.          }  
  24.   
  25.      }  
  26.      public string AddEmployees(Employee Emp)  
  27.      {  
  28.          connection();  
  29.          com = new SqlCommand("InsertData", con);  
  30.          com.CommandType = CommandType.StoredProcedure;  
  31.          com.Parameters.AddWithValue("@FName", Emp.FirstName);  
  32.          com.Parameters.AddWithValue("@Lname", Emp.LastName);  
  33.          com.Parameters.AddWithValue("@Compnay", Emp.Company);  
  34.          con.Open();  
  35.          int i = com.ExecuteNonQuery();  
  36.          con.Close();  
  37.        
  38.          if (i >= 1)  
  39.          {  
  40.              return "New Employee Added Successfully"; 
  41.          }  
  42.          else  
  43.          {  
  44.              return "Employee Not Added"; 
  45.          }         
  46.      } 
 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 DisplayingFormDataUsingWebAPI  
  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.         public IEnumerable<Employee> GetAllEmp()  
  25.         {  
  26.             connection();      
  27.           com = new SqlCommand("select *from Employee", con);  
  28.           com.CommandType = CommandType.Text;  
  29.             SqlDataAdapter da = new SqlDataAdapter(com);  
  30.             DataTable dt = new DataTable();  
  31.             con.Open();  
  32.             da.Fill(dt);  
  33.             con.Close();  
  34.   
  35.             foreach (DataRow row in dt.Rows)  
  36.             {  
  37.                 yield return new Employee  
  38.                 {  
  39.                     Id = Convert.ToInt32(row["Id"]),  
  40.                     FirstName = Convert.ToString(row["FirstName"]),  
  41.                     LastName = Convert.ToString(row["LastName"]),  
  42.                     Company = Convert.ToString(row["Company"]),  
  43.   
  44.                 };  
  45.             }  
  46.   
  47.         }  
  48.         public string AddEmployees(Employee Emp)  
  49.         {  
  50.             connection();  
  51.             com = new SqlCommand("InsertData", con);  
  52.             com.CommandType = CommandType.StoredProcedure;  
  53.             com.Parameters.AddWithValue("@FName", Emp.FirstName);  
  54.             com.Parameters.AddWithValue("@Lname", Emp.LastName);  
  55.             com.Parameters.AddWithValue("@Compnay", Emp.Company);  
  56.             con.Open();  
  57.             int i = com.ExecuteNonQuery();  
  58.             con.Close();  
  59.           
  60.             if (i >= 1)  
  61.             {  
  62.                 return "New Employee Added Successfully";  
  63.   
  64.             }  
  65.             else  
  66.             {  
  67.                 return "Employee Not Added";  
  68.   
  69.             }            
  70.         }  
  71.     }  

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:
  1. //creating the object of EmpRepository class  
  2.       static EmpRepository repository = new EmpRepository();  
  3.   
  4.       public IEnumerable<Employee> GetAllEmp()  
  5.       {  
  6.           var users = repository.GetAllEmp();  
  7.           return users;  
  8.       }  
  9.       public string AddEmployees(Employee Emp)  
  10.       {  
  11.           //calling EmpRepository Class Method and storing Repsonse   
  12.           var response = repository.AddEmployees(Emp);  
  13.           return response;  
  14.   
  15.       } 
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:
  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 DisplayingFormDataUsingWebAPI  
  9. {  
  10.     public class EmpController : ApiController  
  11.     {  
  12.   
  13.         //creating the object of EmpRepository class  
  14.         static EmpRepository repository = new EmpRepository();  
  15.   
  16.         public IEnumerable<Employee> GetAllEmp()  
  17.         {  
  18.             var users = repository.GetAllEmp();  
  19.             return users;  
  20.         }  
  21.         public string AddEmployees(Employee Emp)  
  22.         {  
  23.             //calling EmpRepository Class Method and storing Repsonse   
  24.             var response = repository.AddEmployees(Emp);  
  25.             return response;  
  26.   
  27.         }  
  28.   
  29.     }  

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:
  1. <script type="text/javascript">  
  2.      function GetAllEmp() {  
  3.            $.getJSON("api/Emp"function (data) {  
  4.                $('#bindemp').empty();  
  5.                $.each(data, function (key, val) {  
  6.                  
  7.                    var row = "<tr><td>" + val.Id + "</td> <td></td>  <td>" + val.FirstName + "  " + val.LastName + "</td> <td></td> <td>" + val.Company +  
  8.                        "</td></tr>";  
  9.   
  10.                    $(row).appendTo($('#bindemp'));  
  11.   
  12.                });  
  13.            });  
  14.        }        
  15.        function AddEmp() {  
  16.            
  17.            var Emp = {};  
  18.            Emp.FirstName = $("#txtFirstName").val();  
  19.            Emp.LastName = $("#txtLastName").val();           
  20.            Emp.Company = $("#txtCompany").val();  
  21.   
  22.            $.ajax({  
  23.                url:"<%=Page.ResolveUrl("/api/Emp/AddEmployees")%>",   
  24.                type: "POST",  
  25.                contentType: "application/json;charset=utf-8",  
  26.                data: JSON.stringify(Emp),  
  27.                dataType: "json",  
  28.                success: function (response) {  
  29.   
  30.                    alert(response);  
  31.                 GetAllEmp();
  32.                },  
  33.   
  34.                error: function (x, e) {  
  35.                    alert('Failed');  
  36.                    alert(x.responseText);  
  37.                    alert(x.status);  
  38.   
  39.                }  
  40.            });  
  41.        }
  42.        $(document).ready(function ()  
  43.         {  
  44.   
  45.           GetAllEmp();  
  46.   
  47.            $("#btnSave").click(function (e) {
  48.                AddEmp();  
  49.                e.preventDefault();
  50.            });
  51.        });  
  52.   
  53.    </script> 
Now the entire default.aspx page will be as follows: 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DisplayingFormDataUsingWebAPI.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.       function GetAllEmp() {  
  12.             $.getJSON("api/Emp", function (data) {  
  13.                 $('#bindemp').empty();  
  14.                 $.each(data, function (key, val) {  
  15.                   
  16.                     var row = "<tr><td>" + val.Id + "</td> <td></td>  <td>" + val.FirstName + "  " + val.LastName + "</td> <td></td> <td>" + val.Company +  
  17.                         "</td></tr>";  
  18.   
  19.                     $(row).appendTo($('#bindemp'));  
  20.   
  21.                 });  
  22.             });  
  23.         }  
  24.          
  25.         function AddEmp() {  
  26.             
  27.             var Emp = {};  
  28.             Emp.FirstName = $("#txtFirstName").val();  
  29.             Emp.LastName = $("#txtLastName").val();           
  30.             Emp.Company = $("#txtCompany").val();  
  31.   
  32.             $.ajax({  
  33.                 url:"<%=Page.ResolveUrl("/api/Emp/AddEmployees")%>",   
  34.                 type: "POST",  
  35.                 contentType: "application/json;charset=utf-8",  
  36.                 data: JSON.stringify(Emp),  
  37.                 dataType: "json",  
  38.                 success: function (response) {  
  39.   
  40.                     alert(response);  
  41.                  GetAllEmp();       
  42.   
  43.                 },  
  44.                 error: function (x, e) {  
  45.                     alert('Failed');  
  46.                     alert(x.responseText);  
  47.                     alert(x.status);  
  48.                 }  
  49.             });
  50.   
  51.         }
  52.   
  53.         $(document).ready(function ()  
  54.          {
  55.            GetAllEmp();
  56.             $("#btnSave").click(function (e) {      
  57.   
  58.                 AddEmp();  
  59.                 e.preventDefault();
  60.             });
  61.         });
  62.     </script>  
  63. </head>  
  64. <body style="background-color:navy;color:White">  
  65.     <form id="form1" runat="server">  
  66.     <br /><br />  
  67.     <table>  
  68.         <tr>  
  69.             <td>  
  70.                 First Name  
  71.             </td>  
  72.             <td>  
  73.                 <asp:TextBox runat="server" ID="txtFirstName" />  
  74.             </td>  
  75.         </tr>  
  76.         <tr>  
  77.             <td>  
  78.                 Last Name  
  79.             </td>  
  80.             <td>  
  81.                 <asp:TextBox runat="server" ID="txtLastName" />  
  82.             </td>  
  83.         </tr>  
  84.         <tr>  
  85.             <td>  
  86.                 Company  
  87.             </td>  
  88.             <td>  
  89.                 <asp:TextBox runat="server" ID="txtCompany" />  
  90.             </td>  
  91.         </tr>  
  92.         <tr>  
  93.             <td>  
  94.             </td>  
  95.             <td>  
  96.                 <asp:Button Text="Save" runat="server" ID="btnSave" />  
  97.             </td>  
  98.         </tr>  
  99.         </table>  
  100.         <br />  
  101.         <table>  
  102.         
  103.         <thead>  
  104.             <tr>  
  105.                 <td>  
  106.                     Id  
  107.                 </td>  
  108.                <td></td>  
  109.                
  110.                 <td>  
  111.                   Name  
  112.                 </td>  
  113.                  <td></td>  
  114.                 <td>  
  115.                     Company  
  116.                 </td>  
  117.             </tr>  
  118.         </thead>  
  119.        
  120.         <tbody id="bindemp">  
  121.         </tbody>  
  122.     </table>  
  123.     
  124.     </form>  
  125. </body>  
  126. </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
  • 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 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.

Up Next
    Ebook Download
    View all
    Learn
    View all