How To Retrieve Data Using AJAX In ASP.NET

Introduction

In this post we will discuss how to retrieve data from SQL server using Ajax and web service in asp.net.

Step 1

Create a database in the SQL server of your choice:

  1. CREATE TABLE [dbo].[Employee](  
  2.     [ID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [nvarchar](50) NULL,  
  4.     [Position] [nvarchar](50) NULL,  
  5.     [Office] [nvarchar](50) NULL,  
  6.     [Age] [int] NULL,  
  7.     [Salary] [int] NULL,  
  8.  CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
  9. (  
  10.     [ID] ASC  
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
  12. ) ON [PRIMARY]  
  13.   
  14. CREATE procedure [dbo].[spGetAllEmployee]  
  15. as  
  16. begin  
  17. select ID,Name,Position,Office,Age,Salary from employee  
  18. end  

Step 2

Create an empty project in visual studio,  give it a meaningful name and add connection webconfig file. Change data source and database name.

  1. <connectionStrings>  
  2.   <add name="DBCS" connectionString="data source=FARHAN\SQLEXPRESS; database=Demo; integrated security=true;"/>  
  3. </connectionStrings>  

Step 3

Create class in project -- right click, add new item, choose class, and  give it a meaningful name.

  1. public class EmployeesRecord  
  2. {  
  3.     public int ID { get; set; }  
  4.     public string Name { get; set; }  
  5.     public string Position { get; set; }  
  6.     public string Office { get; set; }  
  7.     public int Age { get; set; }  
  8.     public int Salary { get; set; }  
  9. }  

Step 4

Create web service in project; right click, add new item, choose web service.asmx, and  give it a meaningful name.

Add namespace

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Script.Serialization;
  1. [WebMethod]  
  2.         public void GetAllEmployee()  
  3.         {  
  4.             List<EmployeesRecord> employeelist = new List<EmployeesRecord>();  
  5.   
  6.             string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  7.             using (SqlConnection con=new SqlConnection(CS))  
  8.             {  
  9.                 SqlCommand cmd = new SqlCommand("spGetAllEmployee", con);  
  10.                 cmd.CommandType = CommandType.StoredProcedure;  
  11.                 con.Open();  
  12.   
  13.                 SqlDataReader rdr = cmd.ExecuteReader();  
  14.   
  15.                 while (rdr.Read())  
  16.                 {  
  17.                     EmployeesRecord employee = new EmployeesRecord();  
  18.                     employee.ID = Convert.ToInt32(rdr["ID"]);  
  19.                     employee.Name = rdr["Name"].ToString();  
  20.                     employee.Position = rdr["Position"].ToString();  
  21.                     employee.Office = rdr["Office"].ToString();  
  22.                     employee.Age = Convert.ToInt32(rdr["Age"]);  
  23.                     employee.Salary= Convert.ToInt32(rdr["Salary"]);  
  24.   
  25.                     employeelist.Add(employee);  
  26.                 }  
  27.             }  
  28.   
  29.             JavaScriptSerializer js = new JavaScriptSerializer();  
  30.             Context.Response.Write(js.Serialize(employeelist));  
  31.         }  

Step 5

Create web form in project; right click, add new item, choose web form, and  give it a  meaningful name.

Add script cdn link in head section:

  1. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">  
  2. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  
  3. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>  

Write script to call web service to retrieve data from the SQL server:

  1. <script type="text/javascript">  
  2.         $(document).ready(function () {  
  3.             $.ajax({  
  4.                 url: 'EmployeeService.asmx/GetAllEmployee',  
  5.                 dataType: "json",  
  6.                 method: 'post',  
  7.                 success: function (data) {  
  8.                     var employeeTable = $('#tblEmployee tbody');  
  9.                     employeeTable.empty();  
  10.                     $(data).each(function (index, emp) {  
  11.                         employeeTable.append('<tr><td>' + emp.ID + '</td><td>'  
  12.                             + emp.Name + '</td><td>' + emp.Position + '</td><td>' + emp.Office  
  13.                             + '</td><td>' + emp.Age + '</td><td>' + emp.Salary + '</td></tr>');  
  14.                     });  
  15.                 },  
  16.                 error: function (err) {  
  17.                     alert(err);  
  18.                 }  
  19.             });  
  20.         });  
  21.     </script>  

Step 6

Design an html table to display data:

  1. <body>  
  2.     <form id="form1" runat="server">  
  3.         <div class="container">  
  4.             <h3 class="text-uppercase text-center">How to retrive data using ajax in asp.net</h3>  
  5.             <table id="tblEmployee" class="table table-bordered">  
  6.                 <thead class="bg-primary text-white">  
  7.                     <tr>  
  8.                         <th>ID</th>  
  9.                         <th>Name</th>  
  10.                         <th>Position</th>  
  11.                         <th>Office</th>  
  12.                         <th>Age</th>  
  13.                         <th>Salary</th>  
  14.                     </tr>  
  15.                 </thead>  
  16.                 <tbody></tbody>  
  17.             </table>  
  18.         </div>  
  19.     </form>  
  20. </body>  
Step 7

Run project ctr+F5

Final output

Final output