How To Fetch Data From The Database Using AngularJS In Web API

Background

We know AngularJS is a client-side script. So, we cannot use it on server side. In this article, we will fetch the data from database so we will use SQL Server database and the data will be called from database in server side by using web API. The client side will be called using AngularJS. After getting all the data, we will bind it within HTML table.

Sounds good? Here I am going to use Visual Studio Application.

Now, we will go create our application. I hope you will like this.

You can always download the source code here.

Firstly, we will create a database. The following query can be used to create a database in our SQL Server.

To create Database
  1. CREATE DATABASE SchoolMangement;  
  2. To create Table  
  3. USE [SchoolMangement]  
  4. GO  
  5. /****** Object: Table [dbo].[tbl_Student] Script Date: 7/24/2016 11:12:09 PM ******/  
  6. SET ANSI_NULLS ON  
  7. GO  
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10. CREATE TABLE [dbo].[tbl_Student](  
  11. [StudentID] [int] IDENTITY(1,1) NOT NULL,  
  12. [FirstName] [nvarchar](50) NULL,  
  13. [LastName] [nvarchar](50) NULL,  
  14. [Email] [nvarchar](50) NULL,  
  15. [Address] [nvarchar](250) NULL,  
  16. CONSTRAINT [PK_tbl_Student] PRIMARY KEY CLUSTERED   
  17. (  
  18. [StudentID] ASC  
  19. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  20. ON [PRIMARY]  
  21.   
  22. GO  
Now, database has been created. Finally, we get the table like,

database
We can now insert the data in database.
  1. INSERT [dbo].[tbl_Student] ([StudentID], [FirstName], [LastName], [Email], [Address]) VALUES (1, N'Parvaz', N'Reza', N'[email protected]', N'Amla,Kushtia')  
  2. GO  
  3. INSERT [dbo].[tbl_Student] ([StudentID], [FirstName], [LastName], [Email], [Address]) VALUES (2, N'Mamun', N'Uddin', N'[email protected]', N'mirpur,Kushtia')  
  4. GO  
  5. INSERT [dbo].[tbl_Student] ([StudentID], [FirstName], [LastName], [Email], [Address]) VALUES (3, N'Seam', N'Alli', N'[email protected]', N'Dhaka,Bangladesh')  
Creating MVC Application

Click File >> New >> Project. Select ASP.NET web application. Give project a name, location and click OK. From the following pop up, we will select the MVC. Also, we select the core references and folders for MVC and Web API.

MVC application

Once you click OK, a project with MVC will be created for you. You can see its folder structure with core references.

structure

We will setup AngularJS. If you do not know how to setup AngularJS, click here. after setting up the AngularJS, we will create a data model.

Create Entity Data Model

Right click on your Models folder and click New. Select ADO.NET Entity Data Model. Follow the steps given. Once you are done with the process, you can see the edmx file and other files in your Models folder. Here, I gave SchoolMangementEntities for our Entity Data Model name. Now, you can see that a file with edmx extension have been created.

Create Controller

Right click on your Controller folder and select Add, click Controller, select MVC 5 Controller- Empty and name it as StudentController.
  1. public class StudentController : Controller  
  2.     {  
  3.         //  
  4.         // GET: /Student/  
  5.         public ActionResult Index()  
  6.         {  
  7.             return View();  
  8.         }  
  9.     }  
Create View

Right click on Index Method which we have in StudentController. Click on Add View. Follow the steps given
  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4.   
  5. <h2>Index</h2>  
Create Web API Controller

We will create a folder for API in our project named "API". Right click on API folder, select add, click controller, select Web API 2 Controller-Empty and give it name as "StudentController".
  1. public class StudentController : ApiController  
  2.     {  
  3.         SchoolMangementEntities _ctx = null// SchoolMangementEntities is data model name  
  4.          
  5.         public StudentController()  
  6.         {  
  7.             _ctx = new SchoolMangementEntities();  
  8.         }  
  9.         public List<tbl_Student> GetStudents()  
  10.         {  
  11.             List<tbl_Student> students = null;  
  12.             try  
  13.             {  
  14.                 students = _ctx.tbl_Student.ToList();  
  15.             }  
  16.             catch   
  17.             {  
  18.                 students = null;  
  19.             }  
  20.             return students;  
  21.         }  
  22.     }  

So, the coding part to fetch the data from the database is ready. Now, we need to check whether our Web API is ready for action. To check that, you just need to run the URL:

http://localhost:10956/api/student/GetStudents

code

Now, we will start our AngularJS part.

Right click on Modules folder. Select JavaScript file. Give it name as "app.js" which we have in ScriptsNg folder. Write the following code in this file.
  1. var app;  
  2. (function () {  
  3.     'use strict'//Defines that JavaScript code should be executed in "strict mode"  
  4.     app = angular.module('myapp', []);  
  5. })();  
We create custom service here. Right click on Services folder, select JavaScript file, name it as “StudentService” which we have in ScriptsNg folder. Write the following code in this file.
  1. app.service('StudentService'function ($http) {  
  2.     //**********----Get All Record----***************  
  3.     var urlGet = '';  
  4.     this.getAll = function (apiRoute) {  
  5.         urlGet = apiRoute;  
  6.         return $http.get(urlGet);  
  7.     }  
  8. });  
We create StudentController now. Right click on Controller folder, select JavaScript file, name it as "StudentController” which we have in ScriptsNg folder. Write the following code in this file.
  1. app.controller('StudentCtrl', ['$scope''StudentService',  
  2.     // we inject StudentService  inject becuse we call getAll method for get all student  
  3. function ($scope, StudentService) {  
  4.     // this is base url   
  5.     var baseUrl = '/api/student/';  
  6.     // get all student from databse  
  7.     $scope.getStudents=function()  
  8.     {  
  9.         var apiRoute = baseUrl + 'GetStudents/';  
  10.         var _student = StudentService.getAll(apiRoute);  
  11.         _student.then(function (response) {  
  12.             $scope.students = response.data;  
  13.         },  
  14.         function (error) {  
  15.             console.log("Error: " + error);  
  16.         });  
  17.   
  18.     }  
  19.     $scope.getStudents();  
  20.   
  21. }]);  
Now, we will work on the Index View which we have created.
  1. <div ng-app="myapp">  
  2.     <div ng-controller="StudentCtrl">  
  3.         <table class="table table-striped table-bordered table-hover table-checkable datatable">  
  4.             <thead class="grid-top-panel">  
  5.                 <tr>  
  6.                     <th>StudentID</th>  
  7.                     <th>First Name</th>  
  8.                     <th>LastName</th>  
  9.                     <th>Email</th>  
  10.                 </tr>  
  11.             </thead>  
  12.             <tbody>  
  13.                 <tr ng-repeat="dataModel in students">  
  14.                     <td>{{dataModel.StudentID}}</td>  
  15.                     <td>{{dataModel.FirstName}}</td>  
  16.                     <td>{{dataModel.LastName}}</td>  
  17.                     <td>{{dataModel.Email}}</td>  
  18.                 </tr>  
  19.             </tbody>  
  20.         </table>  
  21.     </div>  
  22. </div>  
  23. <script src="~/Scripts/angular.min.js"></script>  
  24. <script src="~/ScriptsNg/Module/app.js"></script>  
  25. <script src="~/ScriptsNg/Controller/StudentController.js"></script>  
  26. <script src="~/ScriptsNg/Services/StudentService.js"></script>  
Finally, we get the result.
 
result

Up Next
    Ebook Download
    View all
    Learn
    View all