Click here to Skip to main content
15,868,154 members
Articles / Web Development / HTML

Crud Operation using Angular JS and Web API

Rate me:
Please Sign up or sign in to vote.
4.83/5 (43 votes)
4 Dec 2016CPOL5 min read 95.2K   5.1K   61   21
In this article, we will learn basic CRUD operation using AngularJS and Web API with a sample application.

In this article, we will learn basic CRUD operation using AngularJS and Web API with a sample application.

In this article, we are going to explore how to:

  • use Database SQL Server
  • use MVC Application
  • use Entity Framework (Database First Approach)
  • use angularJS
  • use ASP.NET Web API

Let’s Get Started with the Steps

Create Database: Before we get started with IDE, let’s create a new database named “StudentDB” and create a sample table named “tblStudent”. The script is given below:

SQL
USE [StudentDB ]
GO

/****** Object:  Table [dbo].[tblStudent]    Script Date: 11/24/2016 1:36:13 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[tblStudent](
	[StudentID] [int] IDENTITY(1,1) NOT NULL,
	[FirstName] [nvarchar](50) NULL,
	[LastName] [nvarchar](50) NULL,
	[Email] [nvarchar](50) NULL,
	[Address] [nvarchar](50) NULL,
 CONSTRAINT [PK_tblStudent] 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]

GO

We have done our database. Now let’s go for creating a simple MVC application Start Visual Studio, click New Project >>

Image 1

The below window will appear on screen:

Image 2

After clicking, a new ASP.NET Project window will appear on screen:

Image 3

Solution creation is done with loading all needed files. Given below is the picture of solution structure.

Image 4

Let's go Explore Solution Structure

We know that the ASP.NET MVC is a web application framework developed by Microsoft. This structure works with Model, View, and Controller.

  • Model: Classes that represent the data of the solution and it enforces business.
  • View: Simple world view means UI (User Interface) which dynamically generates HTML responses.
  • Controller: A Controller is the link between User and System. It handles incoming browser requests and after process using model data or specific task, returns a response to the browser.

Now We Will Add AngularJS in Our Solution

Right button click on solution, and click Manage NuGet Packages for adding Angular JS reference.

Image 5

After clicking the Install button, load the AngularJS files. Below is the picture:

Image 6

Now, we will create ScriptsNg folder in solution, we will create 4 folders within ScriptsNg.

  1. Controller
  2. Directive
  3. Module
  4. Service

Controller: AngularJS Controller Control Data between model and view in application, keep all Controller Script files within Controller folder.

Directive: Angular JS Directive extends HTML with a new attribute, keeping all Directive files within Directive Folder.

Module: Modules are used to separate logic, say services, controllers, application, etc. and keep the code clean, keep all module files in module folder.

Service: Service is function, keep all customized service files within Service Folder. Now, we will create a JS file named “app.js” within module folder. Given The code is given below:

JavaScript
var app;
(function () {
    'use strict'; //Defines that JavaScript code should be executed in "strict mode"
    app = angular.module('myapp', []);
})();

We will create Controller named “StudentCtrl” within Controller folder. The code is given below:

JavaScript
app.controller('StudentCtrl', ['$scope',
    function ($scope) {
        $scope.Message = 'Hellow World';
    }]);

We will create StudentController class within MVC Controller folder. The code is given below:

JavaScript
public class StudentController : Controller
    {
        // GET: Student
        public ActionResult Index()
        {
            return View();
        }
    }

We have to create view. Below is picture on how to create view.

Image 7

View has been created successfully. We will add some code within index view for checking what angularJS will work. The code is given below.

HTML
<div ng-app="myapp">
    <div ng-controller="StudentCtrl">
        {{Message}}

    </div>
</div>

<script src="~/Scripts/angular.min.js"></script>
<script src="~/ScriptsNg/Module/app.js"></script>
<script src="~/ScriptsNg/Controller/StudentCtrl.js"></script>

After running Angular JS, the work has been done. Below is the result:

Image 8

Entity Framework: After clicking References, we can see that Entity Framework already exists in our solution.

Create Entity Data Model: Right click on your model folder and click new, select ADO.NET Entity Data Model. Follow the steps given. Once you have done the process, we can see the edmx file and other files in your model folder. It is named StudentDBEntities. Below is the picture of edmx model.

Image 9

Now our solution is ready for crud operation.

Now, we have created a folder named api in our solution. Right button click, click add and click controller, then show the below window:

Image 10

Add controller name. The image is shown below:

Image 11

Our StudentController's API has been created.

For Save

C#
namespace CrudOperation.api
{
    // Route 
    [RoutePrefix("/api/Student")]
    public class StudentController : ApiController
    {
         // StudentDBEntities object point
        StudentDBEntities dbContext = null;
        // Constructor 
        public StudentController()
        {
            // create instance of an object
            dbContext = new StudentDBEntities();
        }        
        [ResponseType(typeof(tblStudent))]
        [HttpPost]
        public HttpResponseMessage SaveStudent(tblStudent astudent)
        {
            int result = 0;
            try
            {
                dbContext.tblStudents.Add(astudent);
                dbContext.SaveChanges();
                result = 1;
            }
            catch (Exception e)
            {

                result = 0;
            }

            return Request.CreateResponse(HttpStatusCode.OK, result);
        }
    }
}

We have completed the save method of student. We have added some code within studentCtrl. The code is given below:

JavaScript
app.controller('StudentCtrl', ['$scope', 'CrudService',
    function ($scope, CrudService) {

        // Base Url 
        var baseUrl = '/api/Student/';
        $scope.btnText = "Save";
        $scope.studentID = 0;
        $scope.SaveUpdate = function () {
            var student = {
                FirstName: $scope.firstName,
                LastName: $scope.lasttName,
                Email: $scope.email,
                Address: $scope.adress,
                StudentID: $scope.studentID
            }
            if ($scope.btnText == "Save") {
                var apiRoute = baseUrl + 'SaveStudent/';
                var saveStudent = CrudService.post(apiRoute, student);
                saveStudent.then(function (response) {
                    if (response.data != "") {
                        alert("Data Save Successfully");                       
                        $scope.Clear();

                    } else {
                        alert("Some error");
                    }

                }, function (error) {
                    console.log("Error: " + error);
                });
            }
        }

        $scope.Clear = function () {
            $scope.studentID = 0;
            $scope.firstName = "";
            $scope.lasttName = "";
            $scope.email = "";
            $scope.adress = "";
        }

        }]);

In the above code, we can see "CrudService" is service we have written some HTTP Verb for insert, update, delete, and fetch data from database. The code is given below:

JavaScript
app.service('CrudService', function ($http) {

    var urlGet = '';
    this.post = function (apiRoute, Model) {
        var request = $http({
            method: "post",
            url: apiRoute,
            data: Model
        });
        return request;
    }
    this.put = function (apiRoute, Model) {
        var request = $http({
            method: "put",
            url: apiRoute,
            data: Model
        });
        return request;
    }
    this.delete = function (apiRoute) {
        var request = $http({
            method: "delete",
            url: apiRoute
        });
        return request;
    }
    this.getAll = function (apiRoute) {

        urlGet = apiRoute;
        return $http.get(urlGet);
    }

    this.getbyID = function (apiRoute,studentID) {

        urlGet = apiRoute + '/' + studentID;
        return $http.get(urlGet);
    }
});

We have to design our UI (User Interface) for Crud Operation. Above, we have already created index view. Now, we will use this view. The code is given below:

HTML
<div ng-app="myapp">
    <div ng-controller="StudentCtrl">
        <form novalidate name="frmStudent" id="frmStudent" class="form-horizontal row-border">
            <br />
            <div class="col-md-12">
                <div class="form-group">
                    <label class="col-md-4 control-label" for="input17"> First Name</label>
                    <div class="col-md-7">
                        <input type="text"
                               id="idFirstName"
                               class="form-control"
                               name="nameFirstName" ng-model="firstName" />
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-4 control-label" for="input17"> Last Name</label>
                    <div class="col-md-7">
                        <input type="text"
                               id="idLastName"
                               class="form-control"
                               name="nameFirstName" ng-model="lasttName" />
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-4 control-label" for="input17"> Email</label>
                    <div class="col-md-7">
                        <input type="text"
                               id="idEmail"
                               class="form-control"
                               name="nameEmail" ng-model="email" />
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-4 control-label" for="input17"> Address</label>
                    <div class="col-md-7">
                        <input type="text"
                               id="idAddress"
                               class="form-control"
                               name="nameAdress" ng-model="adress" />
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-4">
                        </div>
                        <div class="col-md-7">
                            <span id="save" class="btn btn-success margin-right-btn" 
                             ng-click="SaveUpdate()">
                                <i class="icon-save"></i> {{btnText}}
                            </span>
                        </div>
                    </div>
            </div>            
        </form>
    </div>
</div>

<script src="~/Scripts/angular.min.js"></script>
<script src="~/ScriptsNg/Module/app.js"></script>
<script src="~/ScriptsNg/Controller/StudentCtrl.js"></script>
<script src="~/ScriptsNg/Services/CrudService.js"></script>

Let’s go explain the code: In the above code, we can see that there are some unfamiliar things that are used for Angular JS.

  • ng-app="myapp": Here ng-app is root element of the angularJS and “myapp" is the name of app.js.
  • ng-controller="StudentCtrl": Here ng-controller directive adds a controller to your application and StudentCtrl is the name of controller. We can write code and make function and variables.
  • ng-model: Here, directive binds the value of HTML controls.

Note: Keep in mind that Angular JS two are way data bind. After running, we get the below UI.

Image 12

For Fetch Data form Database

Our Save is done. Now, we will fetch data from database. We will add GetStudents method in StudentController's API Controller. The code is given below:

C#
[ResponseType(typeof(tblStudent))]
       [HttpGet]
       public List<tblStudent> GetStudents()
       {
           List<tblStudent> students = null;
           try
           {
               students = dbContext.tblStudents.ToList();

           }
           catch (Exception e)
           {
               students = null;
           }

           return students;
       }

We have added some code within studentCtrl. The code is given below:

JavaScript
$scope.GetStudents = function () {
            var apiRoute = baseUrl + 'GetStudents/';
            var student = CrudService.getAll(apiRoute);
            student.then(function (response) {
                debugger
                $scope.studnets = response.data;

            },
            function (error) {
                console.log("Error: " + error);
            });


        }
        $scope.GetStudents();

We have added some code Index view for show students list. The code is given below:

HTML
<table class="table table-hover general-table">
                <thead class="grid-top-panel">
                    <tr>
                        <th style="display:none">StudentID</th>                       
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Email</th>
                        <th>Address</th>
                        <th>Action</th>
                        
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="dataModel in students">
                        <td style="display:none">{{dataModel.StudentID}}</td>                        
                        <td> {{dataModel.FirstName}}</td>
                        <td> {{dataModel.LastName}}</td>
                        <td>{{dataModel.Email}}</td>
                        <td>{{dataModel.Address}}</td>
                        <td style="text-align:right; color:white">
                            <span>                                
                                <span id="save" class="btn btn-primary margin-right-btn" 
                                 ng-click="GetStudentByID(dataModel)">
                                     Edit
                                </span>
                            </span>
                        </td>
                        <td style="text-align:right; color:white">
                            <span>
                                <span id="save" class="btn btn-danger margin-right-btn" 
                                 ng-click="DeleteStudent(dataModel)">
                                    Delete
                                </span>
                            </span>
                        </td>
                    </tr>
                </tbody>
                <tfoot></tfoot>
            </table>

We have just added data within the HTML table.

Image 13

For Update

We have to create two methods in StudentController’s API for update, firstly we will get student info by studentID after changing student’s properties, we have to update.

First Method GetStudentByID

C#
[Route("GetStudentByID/{studentID:int}")]
       [ResponseType(typeof(tblStudent))]
       [HttpGet]
       public tblStudent GetStudentByID(int studentID)
       {
           tblStudent astudent = null;
           try
           {
               astudent = dbContext.tblStudents.Where(x => x.StudentID == studentID).SingleOrDefault();
           }
           catch (Exception e)
           {
               astudent = null;
           }

           return astudent;
       }

We have to use GetStudentByID method for getting specific student data by studentID StudentCtrl. The code is given below:

JavaScript
$scope.GetStudentByID = function (dataModel)
        {
            debugger
            var apiRoute = baseUrl + 'GetStudentByID';
            var student = CrudService.getbyID(apiRoute, dataModel.StudentID);
            student.then(function (response) {
                $scope.studentID = response.data.StudentID;
                $scope.firstName = response.data.FirstName;
                $scope.lasttName = response.data.LastName;
                $scope.email = response.data.Email;
                $scope.adress = response.data.Address;
                $scope.btnText = "Update";
            },
            function (error) {
                console.log("Error: " + error);
            });
        }

Now, we will check what will work. After clicking edit button, we get the below result:

Image 14

Secondly, we will update our student data so we have to Create UpdateStudent method. The code is given below:

C#
[ResponseType(typeof(tblStudent))]
        [HttpPut]
        public HttpResponseMessage UpdateStudent(tblStudent astudent)
        {
            int result = 0;
            try
            {
                dbContext.tblStudents.Attach(astudent);
                dbContext.Entry(astudent).State = EntityState.Modified;
                dbContext.SaveChanges();
                result = 1;
            }
            catch (Exception e)
            {
                result = 0;
            }

            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

We will modify our SaveUpdate method for update:

JavaScript
$scope.SaveUpdate = function () {
            var student = {
                FirstName: $scope.firstName,
                LastName: $scope.lasttName,
                Email: $scope.email,
                Address: $scope.adress,
                StudentID: $scope.studentID
            }
            if ($scope.btnText == "Save") {
                var apiRoute = baseUrl + 'SaveStudent/';
                var saveStudent = CrudService.post(apiRoute, student);
                saveStudent.then(function (response) {
                    if (response.data != "") {
                        alert("Data Save Successfully");
                        $scope.GetStudents();
                        $scope.Clear();

                    } else {
                        alert("Some error");
                    }

                }, function (error) {
                    console.log("Error: " + error);
                });
            }
            else
            {
                var apiRoute = baseUrl + 'UpdateStudent/';
                var UpdateStudent = CrudService.put(apiRoute, student);
                UpdateStudent.then(function (response) {
                    if (response.data != "") {
                        alert("Data Update Successfully");
                        $scope.GetStudents();
                        $scope.Clear();

                    } else {
                        alert("Some error");
                    }

                }, function (error) {
                    console.log("Error: " + error);
                });
            }
        }

Now, we will check what will work. The image is shown below:

Image 15

For Delete

Now we have to add delete method within StudentController's API. The code is given below:

C#
[ResponseType(typeof(tblStudent))]
        [HttpDelete]
        public HttpResponseMessage DeleteStudent(int id)
        {
            int result = 0;
            try
            {
                var student = dbContext.tblStudents.Where(x => x.StudentID == id).FirstOrDefault();
                dbContext.tblStudents.Attach(student);
                dbContext.tblStudents.Remove(student);
                dbContext.SaveChanges();
                result = 1;
            }
            catch (Exception e)
            {

                result = 0;
            }

            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

We will add Delete method within AngularJs Controller named "StudentCtrl". The code is given below:

JavaScript
$scope.DeleteStudent = function (dataModel)
        {
            debugger
            var apiRoute = baseUrl + 'DeleteStudent/' + dataModel.StudentID;
            var deleteStudent = CrudService.delete(apiRoute);
            deleteStudent.then(function (response) {
                if (response.data != "") {
                    alert("Data Delete Successfully");
                    $scope.GetStudents();
                    $scope.Clear();

                } else {
                    alert("Some error");
                }

            }, function (error) {
                console.log("Error: " + error);
            });
        }

After deleting a student info, the output is displayed in the image below:

Image 16

Hope this will be very helpful. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Amber Software Solution Ltd.
Bangladesh Bangladesh
Hi, I am Shamim Uddin.Working with Microsoft Technologies.

Comments and Discussions

 
QuestionAfter updating Pin
mesay tesfa17-Oct-18 4:27
mesay tesfa17-Oct-18 4:27 
QuestionDownloaded Source Pin
optirob7422-Nov-17 13:47
optirob7422-Nov-17 13:47 
SuggestionRemove Underscore Pin
Imraqau21-Nov-17 22:52
Imraqau21-Nov-17 22:52 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun4-Feb-17 17:53
Humayun Kabir Mamun4-Feb-17 17:53 
SuggestionNice Pin
Florin Balan4-Jan-17 12:38
Florin Balan4-Jan-17 12:38 
GeneralMy vote of 5 Pin
Farhad Reza10-Dec-16 7:26
Farhad Reza10-Dec-16 7:26 
GeneralNice Article Pin
Alireza_13629-Dec-16 18:27
Alireza_13629-Dec-16 18:27 
QuestionDelete not working Pin
abubberman8-Dec-16 22:54
abubberman8-Dec-16 22:54 
QuestionMy vote of 4 Pin
Eriole6-Dec-16 17:58
Eriole6-Dec-16 17:58 
Questionsave doesn't work Pin
wadigzon Diaz-wong6-Dec-16 7:55
wadigzon Diaz-wong6-Dec-16 7:55 
AnswerRe: save doesn't work Pin
Shamim Uddin7-Dec-16 14:54
professionalShamim Uddin7-Dec-16 14:54 
QuestionCross Site attack Pin
Taoufik RIFAI6-Dec-16 4:43
Taoufik RIFAI6-Dec-16 4:43 
QuestionNice article but Pin
lmcgs1-Dec-16 3:51
lmcgs1-Dec-16 3:51 
My vote is 5 but can i ask you something? Why you don't use codefirst?
AnswerRe: Nice article but Pin
Shamim Uddin1-Dec-16 4:16
professionalShamim Uddin1-Dec-16 4:16 
QuestionTyping error on GetStudents Pin
cirelli.alessandro30-Nov-16 23:29
cirelli.alessandro30-Nov-16 23:29 
AnswerRe: Typing error on GetStudents Pin
Shamim Uddin1-Dec-16 4:17
professionalShamim Uddin1-Dec-16 4:17 
AnswerRe: Typing error on GetStudents Pin
charles9226-Feb-18 6:00
charles9226-Feb-18 6:00 
QuestionDelete Function didn't Work Pin
ian sembiring30-Nov-16 22:24
ian sembiring30-Nov-16 22:24 
AnswerRe: Delete Function didn't Work Pin
Shamim Uddin1-Dec-16 4:14
professionalShamim Uddin1-Dec-16 4:14 
GeneralRe: Delete Function didn't Work Pin
ian sembiring1-Dec-16 14:31
ian sembiring1-Dec-16 14:31 
GeneralRe: Delete Function didn't Work Pin
Member 1368125915-Feb-18 23:37
Member 1368125915-Feb-18 23:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.