Click here to Skip to main content
13,344,016 members (99,178 online)
Click here to Skip to main content
Add your own
alternative version

Stats

49.6K views
2.6K downloads
60 bookmarked
Posted 29 Nov 2016

Crud Operation using Angular JS and Web API

, 4 Dec 2016
Rate this:
Please Sign up or sign in to vote.
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:

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 >>

The below window will appear on screen:

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

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

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.

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

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:

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:

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

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

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

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

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

<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:

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.

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:

Add controller name. The image is shown below:

Our StudentController's API has been created.

For Save

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:

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:

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:

<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.

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:

[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:

$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:

<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.

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

[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:

$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:

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

[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:

$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:

For Delete

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

[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:

$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:

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)

Share

About the Author

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

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionDownloaded Source Pin
optirob7422-Nov-17 14:47
memberoptirob7422-Nov-17 14:47 
SuggestionRemove Underscore Pin
Imraqau21-Nov-17 23:52
memberImraqau21-Nov-17 23:52 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun4-Feb-17 18:53
memberHumayun Kabir Mamun4-Feb-17 18:53 
SuggestionNice Pin
Florin Balan4-Jan-17 13:38
memberFlorin Balan4-Jan-17 13:38 
GeneralMy vote of 5 Pin
Forhad Reza10-Dec-16 8:26
memberForhad Reza10-Dec-16 8:26 
GeneralNice Article Pin
Alireza_13629-Dec-16 19:27
memberAlireza_13629-Dec-16 19:27 
QuestionDelete not working Pin
abubberman8-Dec-16 23:54
memberabubberman8-Dec-16 23:54 
QuestionMy vote of 4 Pin
Eriole6-Dec-16 18:58
memberEriole6-Dec-16 18:58 
Questionsave doesn't work Pin
wadigzon Diaz-wong6-Dec-16 8:55
memberwadigzon Diaz-wong6-Dec-16 8:55 
AnswerRe: save doesn't work Pin
Shamim Uddin7-Dec-16 15:54
professionalShamim Uddin7-Dec-16 15:54 
QuestionCross Site attack Pin
Taoufik RIFAI6-Dec-16 5:43
memberTaoufik RIFAI6-Dec-16 5:43 
QuestionNice article but Pin
lmcgs1-Dec-16 4:51
memberlmcgs1-Dec-16 4:51 
AnswerRe: Nice article but Pin
Shamim Uddin1-Dec-16 5:16
professionalShamim Uddin1-Dec-16 5:16 
QuestionTyping error on GetStudents Pin
cirelli.alessandro1-Dec-16 0:29
membercirelli.alessandro1-Dec-16 0:29 
AnswerRe: Typing error on GetStudents Pin
Shamim Uddin1-Dec-16 5:17
professionalShamim Uddin1-Dec-16 5:17 
QuestionDelete Function didn't Work Pin
ian sembiring30-Nov-16 23:24
memberian sembiring30-Nov-16 23:24 
AnswerRe: Delete Function didn't Work Pin
Shamim Uddin1-Dec-16 5:14
professionalShamim Uddin1-Dec-16 5:14 
GeneralRe: Delete Function didn't Work Pin
ian sembiring1-Dec-16 15:31
memberian sembiring1-Dec-16 15:31 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180111.1 | Last Updated 5 Dec 2016
Article Copyright 2016 by Shamim Uddin
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid