CRUD operations in AngularJS and Web API
AngularJS is one of the most popular client-side JavaScript frameworks on the web. It helps us to create Single-Page Application (SPA) using HTML, CSS, and JavaScript. It provides MVC structure for developing SPA applications. ASP.NET Web API is a good choice for providing data for these types of applications. This article explains how to perform CRUD operations using ASP.NET WebAPI and AngularJS.
This can be summarized as like:
This can be summarized as like:
- Table Creations
- Creations of ASP.NET Web API
- Include AngularJS
- Create AngularJS Controller
- Create User Interface
Before starting we need to learn some basic knowledge on Web API, and AngularJS. We can get it from the internet easily. We can perform numerous tasks with the combinations of these three. Let’s consider a table in the database and we want to perform the basic DML operations on that table through web API. We will use AngularJS to communicate between user interface and web API.
Table Creations
Create a Database in the SQL Server named “TestDB”. Create a “Students” table in the database. We can use the following SQL scripts:
Create a Database in the SQL Server named “TestDB”. Create a “Students” table in the database. We can use the following SQL scripts:
CREATE TABLE [dbo].[Students]( [StudentID] [int] IDENTITY(1,1) NOT NULL, [StudentName] [nvarchar](150) NULL, [Address] [nvarchar](200) NULL, [Phone] [nvarchar](50) NULL, CONSTRAINT [PK_member] PRIMARY KEY CLUSTERED ( [StudentID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
Creations of ASP.NET Web API
We can create web API as a separate project or with an ASP.NET MVC project. Let’s start with a a separate project. In order to implement this we need to install Visual Studio 2010/2012, MVC 4.0. All are available on the internet. Here Visual Studio 2010 is used. All the steps are given bellow:
We can create web API as a separate project or with an ASP.NET MVC project. Let’s start with a a separate project. In order to implement this we need to install Visual Studio 2010/2012, MVC 4.0. All are available on the internet. Here Visual Studio 2010 is used. All the steps are given bellow:
Step1
Open Visual Studio and click “New Project” or File -> New Project. In the New Project dialog box:
Open the Visual C# templates
Select the template ASP.NET MVC 4 Web Application
Set the project name to MyWebAPI
Set the disk location to something like C:\TestProject
Click OK
A new window will appear for selecting a sub-template. Multiple sub-options are available like Empty, Internet Application, Web API etc.
Choose “Web API” and click OK button
A default ASP.NET MVC 4 project will be created. It is an MVC application template, so we will find “Model”, “View” and “Controller” folders in the Solution Explorer. If we run this application we will get basic ASP.NET Web API application interface.
Open Visual Studio and click “New Project” or File -> New Project. In the New Project dialog box:
Open the Visual C# templates
Select the template ASP.NET MVC 4 Web Application
Set the project name to MyWebAPI
Set the disk location to something like C:\TestProject
Click OK
A new window will appear for selecting a sub-template. Multiple sub-options are available like Empty, Internet Application, Web API etc.
Choose “Web API” and click OK button
A default ASP.NET MVC 4 project will be created. It is an MVC application template, so we will find “Model”, “View” and “Controller” folders in the Solution Explorer. If we run this application we will get basic ASP.NET Web API application interface.
Step2
Create a connection string in Web.config file. Add the following element to the element in Web.config file:
Create a connection string in Web.config file. Add the following element to the element in Web.config file:
<add name="DBContext" connectionString="Data Source=.;Initial Catalog=TestDB;Persist Security Info=True;User ID=sa;Password=sa123" providerName="System.Data.SqlClient" />
Step3
Create a database model.
In the Solution Explorer right-click the Models folder and select “Add” and “Class”.
Name the class Students.cs and click Add.
Write the following codes inside the class.
Create a database model.
In the Solution Explorer right-click the Models folder and select “Add” and “Class”.
Name the class Students.cs and click Add.
Write the following codes inside the class.
[Key] public int StudentID { get; set; } public string StudentName { get; set; } public string Address { get; set; } public string Phone { get; set; }
Class name should as like our table name. In our Students table we have StudentID, StudentName, Address, Phone field. StudentID is integer and others fields are varchar type.
In our table StudentID is primary key. That’s why have used [Key] to clarify that it is the Primary Key. If the field name is “ID” then we don’t need to use [Key]. [Required] is used for required filed validation. That means StudentName is mandatory.
In our table StudentID is primary key. That’s why have used [Key] to clarify that it is the Primary Key. If the field name is “ID” then we don’t need to use [Key]. [Required] is used for required filed validation. That means StudentName is mandatory.
The following namespace or reference is required for ASP.NET MVC Application using Code First Model.
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
Step4
Need to create a Context class inside the Models folder.
In the Solution Explorer, right-click the Models folder, and select “Add” and Class.
Name the class “DBContext.cs” and click Add.
System.Data.Entity;
Edit the class as like:
Need to create a Context class inside the Models folder.
In the Solution Explorer, right-click the Models folder, and select “Add” and Class.
Name the class “DBContext.cs” and click Add.
System.Data.Entity;
Edit the class as like:
public class DBContext : DbContext { public DbSet<Students> Customers { get; set; } }
The following namespace or reference is may required for ASP.NET MVC Application using Code First Model.
System.Data.Entity;
System.Data.Entity;
DbContext is a built class of .Net. DbContext is a lightweight version of the ObjectContext class. DbContext requires a lot less code for the same kind of functionality. ObjectContext EF V4.0 and DbContext EF V4.1
Step5
We need to create an API Controller for the Student. We can create a Controller by following steps:
Re-Build the project from the menu.
In the Solution Explorer, right-click the Controllers folder, and select Add and Controller
Set controller name to StudentController
Select template: API controller with read/write actions, using Entity Framework
Select model class: Students (MyWebAPI.Models)
Select data context class: DBContext (MyWebAPI.Models)
Click Add
We need to create an API Controller for the Student. We can create a Controller by following steps:
Re-Build the project from the menu.
In the Solution Explorer, right-click the Controllers folder, and select Add and Controller
Set controller name to StudentController
Select template: API controller with read/write actions, using Entity Framework
Select model class: Students (MyWebAPI.Models)
Select data context class: DBContext (MyWebAPI.Models)
Click Add
Visual Studio will create “StudentController.cs” file in the Controllers folder and StudentController Class. This class inherits ApiController class which is responsible for ASP.NET Web API. This class contains all the necessary methods that perform CRUD operations.
We may face a common errors “Context Has Changed Since the Database Was Created”.
To solve this error include the namespace “MyWebAPI.Models;
” and writhe the following code in Application_Start() Method in Global.asax.cs file
Database.SetInitializer(null);
To solve this error include the namespace “MyWebAPI.Models;
” and writhe the following code in Application_Start() Method in Global.asax.cs file
Database.SetInitializer(null);
Our web API is created and now ready for deployment. We can now host it in the IIS and can use with our applications. For simplicity we will not host it and will use this api through a HTML page
Include AngularJS
We need to add AngularJS to the current project. For that, right-click on the project name and select “Manager NuGet Package”. It is also available on the tools menu. From the Package Nuget Manager Window search for AngularJS as shown below and install it to the current project.
We need to add AngularJS to the current project. For that, right-click on the project name and select “Manager NuGet Package”. It is also available on the tools menu. From the Package Nuget Manager Window search for AngularJS as shown below and install it to the current project.
Create AngularJS Controller
We need to include an AngularJS controller. We can use controller in the same UI page or separate JavaScript file. Here we will use separate JavaScript file. Right click on Scripts folder and include a JavaScript file. Keep its name as “StudentController.js”. Write down the following codes.
We need to include an AngularJS controller. We can use controller in the same UI page or separate JavaScript file. Here we will use separate JavaScript file. Right click on Scripts folder and include a JavaScript file. Keep its name as “StudentController.js”. Write down the following codes.
//AngularJS module var app = angular.module('app', []); //AngularJS controller app.controller('StudentController', ['$scope', '$http', StudentController]); //AngularJS controller method function StudentController($scope, $http) { //Select all the data's $http.get('http://localhost:18977/api/student').success(function (data) { $scope.Students = data; }) .error(function () { $scope.error = "An Error has occured while loading posts!"; }); //Select single data $scope.getSingleData = function (Student) { $http.get('http://localhost:18977/api/student/'+ Student.StudentID).success(function (data) { $scope.Student = data; }) .error(function () { $scope.error = "An Error has occured while loading posts!"; }); } //Inser operation $scope.add = function (Student) { $http.post('http://localhost:18977/api/student', Student).success(function (data) { alert("Added successfully!!"); $scope.Students.push(data); ClearFields(); }).error(function (data) { $scope.error = "An error has occured while adding! " + data; }); }; //Edit/Update operation $scope.save = function (Student) { $http.put('http://localhost:18977/api/student/' + Student.StudentID, Student).success(function (data) { alert("Updated successfully!!"); $http.get('http://localhost:18977/api/student').success(function (data) { $scope.Students = data; ClearFields(); }) }).error(function (data) { $scope.error = "An Error has occured while updating! " + data; }); }; //Delete operation $scope.deletecustomer = function (Student) { $http.delete('http://localhost:18977/api/student/' + Student.StudentID).success(function (data) { alert("Deleted successfully!!"); $http.get('http://localhost:18977/api/student').success(function (data) { $scope.Students = data; }) }).error(function (data) { $scope.error = "An error has occured while deleting! " + data; }); }; //Cler inputs function ClearFields() { $scope.Student.StudentID = ""; $scope.Student.StudentName = ""; $scope.Student.Address = ""; $scope.Student.Phone = ""; } }
AngularJS uses some HTTP methods to access web API. Some common HTTP methods are given bellow:
GET : used to get/select data
POST : used to create a new data
PUT : used to update the existing data
DELETE : used to Delete the data
GET : used to get/select data
POST : used to create a new data
PUT : used to update the existing data
DELETE : used to Delete the data
Create User Interface
Right click on the solution explorer and add a HTML documents. Replace it by the following html codes:
Right click on the solution explorer and add a HTML documents. Replace it by the following html codes:
<!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> <title>AngularJS example</title> <script src="Scripts/angular.min.js" type="text/javascript"></script> <script src="Scripts/StudentController.js" type="text/javascript"></script> </head> <body data-ng-app="app" data-ng-controller="StudentController"> <h1>Student Information</h1> <form name="myForm"> <table> <tr> <td> ID </td> <td> Name </td> <td> Address </td> <td> Phone </td> <td> </td> <td> </td> </tr> <tr data-ng-repeat="std in Students"> <td> {{std.StudentID}} </td> <td> {{std.StudentName}} </td> <td> {{std.Address}} </td> <td> {{std.Phone}} </td> <td> <input type="submit" id="Edit" value="Edit" data-ng-click="getSingleData(std)"/></td> <td> <input type="submit" id="Delete" value="Delete" data-ng-click="deletecustomer(std)"/></td> </tr> <tr> <td> Student ID</td> <td> <input type="text" data-ng-model="Student.StudentID"/ disabled></td> </tr> <tr> <td> Name</td> <td> <input type="text" data-ng-model="Student.StudentName" required /></td> </tr> <tr> <td> Address</td> <td> <input type="text" data-ng-model="Student.Address" /></td> </tr> <tr> <td> Phone</td> <td> <input type="text" data-ng-model="Student.Phone" /></td> </tr> <tr> <td> </td> <td> <input type="submit" value="Save" data-ng-click="add(Student)" data-ng-disabled="myForm.user.$dirty && myForm.user.$invalid || myForm.Student.StudentName.$dirty && myForm.Student.StudentName.$invalid"/> <input type="submit" value="Update" data-ng-click="save(Student)"/> <input type="reset" value="Clear"/> </td> </tr> </table> </form> </body> </html>
These codes are created with the combination of HTML5 and AngularJS directives.
<script src=”Scripts/angular.min.js” ..</script>-reference of AngularJS
<script src=”Scripts/StudentController.js” …</script>-reference of controller class
data-ng-app=”app” –module name
data-ng-controller=”StudentController” –controller name
{{ }} – AngularJS expression
data-ng-model – AngularJS directives
<script src=”Scripts/StudentController.js” …</script>-reference of controller class
data-ng-app=”app” –module name
data-ng-controller=”StudentController” –controller name
{{ }} – AngularJS expression
data-ng-model – AngularJS directives
View the student.html file in web browser.
In order to entry new records give some data and click Save button.
In order to update any records click Edit button, change as you want, save Update button.
In order to remove records click on Delete button.
In order to entry new records give some data and click Save button.
In order to update any records click Edit button, change as you want, save Update button.
In order to remove records click on Delete button.
In this way we can integrate AngularJS with web API. The AngularJS provides some attractive features to developed interactive internet applications. The performance and efficiency of this type of applications are so good.
No comments