Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Crud Operation using Angular JS and Web API

0.00/5 (No votes)
4 Dec 2016 2  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here