In this post, we will learn how to perform a CRUD (Create, Update, Read, Delete) demo with Angular JS. In this post, we will use our CRUD library from the previous post. It's already added in the source code download link. For this example, we are using MVC application. In this post, I have added a SQL script of employee table and its relative stored procedures, like insert, update, get, get all, delete and add CRUD library reference in MVC project. Let's start a step by step tutorial of Angular CRUD demo.
Database
Step 1
Create employee table.
- CREATE TABLE [dbo].[Employee](
- [ID] [int] IDENTITY(1,1) NOT NULL,
- [Name] [varchar](50) NULL,
- [MobileNo] [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]
- GO
Step 2
Add all CRUD Procedures (Insert, Update, Get, GetAll, Delete).
Insert Employee
- CREATE PROCEDURE [dbo].[Employee_Insert]
- @Name Varchar(50)
- ,@MobileNo Varchar(50)
- ,@OUTVAL Int OUTPUT
- ,@OUTMSG Varchar(100) OUTPUT
- AS
- BEGIN
-
- SET NOCOUNT ON;
-
- INSERT INTO Employee (Name, MobileNo) VALUES (@Name, @MobileNo)
-
- SET @OUTVAL = 1
- SET @OUTMSG = 'Employee Insert Successfully.'
- END
Update Employe
- CREATE PROCEDURE [dbo].[Employee_Update]
- @ID Int
- ,@Name Varchar(50)
- ,@MobileNo Varchar(50)
- ,@OUTVAL Int OUTPUT
- ,@OUTMSG Varchar(100) OUTPUT
- AS
- BEGIN
-
- SET NOCOUNT ON;
-
- UPDATE Employee SET Name = @Name
- , MobileNo = @MobileNo
- WHERE ID = @ID
-
- SET @OUTVAL = 1
- SET @OUTMSG = 'Employee Update Successfully.'
- END
Delete Employee
- CREATE PROCEDURE [dbo].[Employee_Delete]
- @ID Int
- ,@OUTVAL Int OUTPUT
- ,@OUTMSG Varchar(100) OUTPUT
- AS
- BEGIN
-
- SET NOCOUNT ON;
-
- DELETE FROM Employee WHERE ID = @ID
-
- SET @OUTVAL = 1
- SET @OUTMSG = 'Employee Delete Successfully.'
- END
Get Single Employee Record
- CREATE PROCEDURE [dbo].[Employee_Get]
- @ID Int
- AS
- BEGIN
- SET NOCOUNT ON;
-
- SELECT * FROM Employee WHERE ID = @ID
- END
Get All Employee Records
- CREATE PROCEDURE [dbo].[Employee_GetAll]
- AS
- BEGIN
- SET NOCOUNT ON;
-
- SELECT * FROM Employee
- END
After creating the database from the above script, let's start creating our AngularJS MVC project.
Step 1
Open VS and create the project from File -> New -> Project menu.
Step 2
Select ASP.NET Web Application (.NET Framework) to create MVC application and set the name and location of the project.
Step 3
After setting the name and location of the project, it opens another dialog box. From this dialog, select MVC project and click OK.
Step 4
After completing all the above steps, add CRUD Demo library reference in Angular JS MVC Project.
Step 5
Go to Angular JS MVC project Web.config file and add the Connection string.
- <connectionStrings>
- <add name="DefaultConnection" connectionString="Data source=ServerName;Database=DataBase;Uid=UserName;Password=Password" providerName="System.Data.SqlClient" />
- </connectionStrings>
Controller
After adding ConnectionString in Web.Config file, now, go to Controllers -> HomeController. Inside Home, the controller adds the below namespace for accessing classes of JSON, CRUD etc.
- using CURDDemo;
- using System.Data;
- using Newtonsoft.Json;
After doing all the above pieces of stuff, let's start creating methods for CRUD operation.
Method 1
Save employee record in the employee table.
- public JsonResult Save(EmployeeClass modal)
- {
- MEMBERS.SQLReturnMessageNValue mRes = new EmployeeLogic().Employee_Insert(modal);
- return Json(mRes, JsonRequestBehavior.AllowGet);
- }
The input parameter is: EmployeeClass
Note
The above function returns MEMBERS.SQLReturnMessageNValue. This class contains code and message returned from SQL Stored Procedure. This method inserts the record in the employee table.
Method 2
Update employee record in employee table.
- public JsonResult Update(EmployeeClass modal)
- {
- MEMBERS.SQLReturnMessageNValue mRes = new EmployeeLogic().Employee_Update(modal);
- return Json(mRes, JsonRequestBehavior.AllowGet);
- }
The input parameter is: EmployeeClass
Note
Above function return MEMBERS.SQLReturnMessageNValue this class contains code and message return from SQL Store procedure. This method updates record in the employee table.
Method 3
Get the Single record of the employee by employee ID.
- public JsonResult Get(Int32 ID)
- {
- DataTable dt = new EmployeeLogic().Employee_Get(ID);
-
- string convertDataTableToJson = JsonConvert.SerializeObject(dt);
-
- return Json(convertDataTableToJson, JsonRequestBehavior.AllowGet);
- }
An input parameter is: ID (Unique ID of Employee Table)
Note
Above function returns a JSON result. First get employee record in DataTable and convert DataTable to JSON using Newtonsoft.Json then return to view.
Method 4
Get the Single record of the employee by employee ID.
- public JsonResult GetAll()
- {
- DataTable dt = new EmployeeLogic().Employee_GetAll();
-
- string convertDataTableToJson = JsonConvert.SerializeObject(dt);
-
- return Json(convertDataTableToJson, JsonRequestBehavior.AllowGet);
- }
Note
Above function returns JSON result. This function gets all the employee records in the DataTable and converts DataTable to JSON and returns to view.
Method 5
Delete the employee record by employee ID.
- public JsonResult Delete(Int32 ID)
- {
- MEMBERS.SQLReturnMessageNValue mRes = new EmployeeLogic().Employee_Delete(ID);
- return Json(mRes, JsonRequestBehavior.AllowGet);
- }
An input parameter is: ID (Unique ID of Employee Table)
Note
Above function returns MEMBERS.SQLReturnMessageNValue. This class contains code and message returns from SQL Store procedure. This method deletes the record from the employee table.
View
After adding all the above methods in controller let's start coding in MVC View.
First, we set the title tag of view.
- @{
- ViewBag.Title = "CURD Operation With Angular";
- }
Let's design one form that contains below HTML element.
- Hidden field for employee unique id : ng-model="EmpID".
- Textbox one for employee name : ng-model="EmployeeName".
- Textbox two for employee mobile no : ng-model="MobileNo".
- Button for save and update employee record.
- Table for display all employee records.
Description of Angular JS directive used in this View.
- Set name of the application using ng-app="myApp".
- Set name of controller using ng-controller="EmployeeCtrl".
- Set ID of HTML element using ng-model="EmployeeName".
- Set ng-click for call Save and Update function using ng-click="Save()".
- Using ng-repeat="c in EmployeeData" bind all employee records in the table.
Note
For getting HTML element value we have to use "ng-model" and using this directive we can get the value of an HTML control.
- <div ng-app="myApp" ng-controller="EmployeeCtrl">
- <input type="hidden" ng-model="EmpID" ng-init="EmpID='0'" />
-
- <div class="row">
- <h3>Employee Form</h3>
- <div class="form-inline">
- <div class="form-group">
- <input type="text" class="form-control" ng-model="EmployeeName" placeholder="Employee Name">
- </div>
- <div class="form-group">
- <input type="text" class="form-control" ng-model="MobileNo" placeholder="Mobile No.">
- </div>
- <button class="btn btn-primary" ng-click="Save()">Save</button>
- </div>
- </div>
- <br />
- <div class="row">
- <h3>Employee Records</h3>
- <table class="table table-bordered">
- <thead>
- <tr>
- <th>ID</th>
- <th>Name</th>
- <th>Mobile No.</th>
- <th>Action</th>
- </tr>
- </thead>
- <tbody>
- <tr ng-repeat="c in EmployeeData">
- <td>{{c.ID}}</td>
- <td>{{c.Name}}</td>
- <td>{{c.MobileNo}}</td>
- <td>
- <button type="button" class="btn btn-primary" id="{{c.ID}}" ng-click="Get(c.ID)">Edit</button>
- <button type="button" class="btn btn-danger" id="{{c.ID}}" ng-click="Delete(c.ID)">Delete</button>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
Angular JS
First, we need to add @section scripts{ } in MVC view for writing our Angular JS code inside this. Section tag adds all code in _Layout.cshtml page run time.
Now, add Angular JS file in section
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
Let's create AngularJs function step by step.
First, set one variable for access application and controller inside this application by adding the line mentioned below.
- var myApp = angular.module("myApp", []);
Using myApp get the controller and create one call back function for getting the scope of the function. Using $scope we can access all HTML controls values.
- myApp.controller("EmployeeCtrl", function ($scope, $http) { });
Write the below function code inside myApp.controller ("EmployeeCtrl", function ($scope, $http) { });
Save / Update Code
-
- $scope.Save = function () {
-
- var id = $scope.EmpID;
-
- if (id == 0) {
- var saveReq = {
- method: "POST",
- url: "/Home/Save",
- data: { ID: $scope.EmpID, Name: $scope.EmployeeName, MobileNo: $scope.MobileNo }
- }
-
- $http(saveReq).then(function (mRes) {
- var o = angular.fromJson(mRes.data)
- alert(o.Outmsg);
- $scope.GetAllEmployee();
- });
- }
- else {
- var updateReq = {
- method: "POST",
- url: "/Home/Update",
- data: { ID: $scope.EmpID, Name: $scope.EmployeeName, MobileNo: $scope.MobileNo }
- }
-
- $http(updateReq).then(function (mRes) {
- var o = angular.fromJson(mRes.data)
- alert(o.Outmsg);
- $scope.GetAllEmployee();
- });
- }
-
- $scope.ClearControls();
- };
Insert Output
Above function calls Save and Update method conditionally. If $scope.EmpID contains "0" Save method is called and $scope.EmpID > "0" so we can call update method. For passing data from view to controller use "data:" parameter of saveReq after that call this request using $http. If the request is successfully called then it returns a message from method. Now convert this result and access its parameters.
Get Single Record Code
-
- $scope.Get = function (id) {
- var getReq = {
- method: "POST",
- url: "/Home/Get",
- data: { ID: id }
- }
-
- $http(getReq).then(function (mRes) {
- $scope.Employee = angular.fromJson(mRes.data);
-
- $scope.EmpID = $scope.Employee[0].ID;
f- $scope.EmployeeName = $scope.Employee[0].Name;
- $scope.MobileNo = $scope.Employee[0].MobileNo;
- });
- };
Get Output
Above function gets the result by employee ID and converts JSON and stores in Angular JS "$scope.Employee" object now we can use this object for setting value in HTML control.
Get All record code
-
- $scope.GetAllEmployee = function () {
- var getallReq = {
- method: "POST",
- url: "/Home/GetAll",
- data: {}
- }
-
- $http(getallReq).then(function (mRes) {
- $scope.EmployeeData = angular.fromJson(mRes.data);
- });
- };
GetAll Output
The above function retrieves all employee records from the database and returns JSON. After getting JSON we have to convert this into Angular JS list object using "Angular.fromJson(mRes.data);" and pass in "$scope.EmployeeData" this $scope.EmployeeData we are using in table ng-repeat to display all client records.
Call the above function after completing the code,
Delete the employee code,
-
- $scope.Delete = function (id) {
- var updateReq = {
- method: "POST",
- url: "/Home/Delete",
- data: { ID: id }
- }
-
- $http(updateReq).then(function (mRes) {
- var o = angular.fromJson(mRes.data)
- alert(o.Outmsg);
- $scope.GetAllEmployee();
- });
- };
The above function deletes the record of the employee by ID and returns code and message class. Convert that class "angular.fromJson(mRes.data)" and alert Outmsg for the display user-friendly message on the browser screen.
Clear HTML Controls,
-
- $scope.ClearControls = function () {
- $scope.EmpID = 0;
- $scope.EmployeeName = '';
- $scope.MobileNo = '';
- }
Above function clears value of HTML elements.
Note
$scope.GetAllEmployee(); this function is called when the page loads for the first time.
$scope.ClearControls(); this function is called when inserting and updating records.