Getting Started with AngularJS – Update & Delete Operations with Database Connectivity

This article is in continuation with the previous article,Get Started with AngularJS – Create & Read Operations with Database Connectivity. You can go through it by clicking on the following link.

Getting Started with AngularJS – Create & Read Operations with Database Connectivity

In this article,I am going to use solution which is created in the previous article for Create and Read Operations.

Note:-

In the previous article,we have created an Empty MVC application and added an API Controller with the name PersonsController in the Controllers folder.
Also, added an ASP.Net Entity Data Model for accessing Relational Objects.
Person.html file contains html mark up and angular script for Create and Read Operations.

Get Started:-

let’s go through the implementation of Update and Delete operations.Open the PersonsController.cs file and add the following two methods.

PersonsController.cs-

        //PUT api/person
        //Updating a person
        [HttpPut]
        public HttpResponseMessage PutPerson(person p)
        {
            OrganizationEntities context = new OrganizationEntities();
            person _per = context.people.Find(p.Id);
            if (_per == null)
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            _per.Name = p.Name;
            _per.Age = p.Age;
            _per.Gender = p.Gender;

            try
            {
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }
            return new HttpResponseMessage(HttpStatusCode.OK);
        }

        //DELETE api/person
        //Deleting a person
        [HttpDelete]
        public HttpResponseMessage DeleteProduct(int id)
        {
            OrganizationEntities context = new OrganizationEntities();
            person _per = context.people.Find(id);
            if (_per == null)
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            context.people.Remove(_per);
            try
            {
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }
            return new HttpResponseMessage(HttpStatusCode.OK);
        }

Now,Open the Person.html file and update the Scripts Html mark up as shown in the below. In the below Scripts and Mark-up added the code for the Edit,Update and Delete operations.

Person.html-

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>AngularJS - CRUD Demo</title>
    <script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script type="text/javascript">
        //Defining a Angular module
        var myApp = angular.module('myApp', []);

        //Defining a Angular Controller
        myApp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {

            //Retrieving the List of people
            GetPersons();
            //Displaying the Save button
            $scope.DisplaySave = true;
            //Hiding the Update button
            $scope.DisplayUpdate = false;

            function GetPersons() {
                //Defining the $http service for getting the people
                $http({
                    method: 'GET',
                    url: '/api/persons'
                }).
                success(function (data) {
                    if (data != null || data != 'undefined') {
                        //Assigning people data to the $scope variable
                        $scope.persons = data;
                        //Clearing the Person object in create context and Showing default Gender(Male) Checked
                        $scope.newperson = {
                            Id: '',
                            Gender: 'true'
                        };
                    }
                })
                .error(function (error) {
                    //Showing error message
                    $scope.status = 'Unable to retrieve people' + error.message;
                });
            }

            //Create a new person
            $scope.createPerson = function () {
                //Defining $http service for creating a person
                $http({
                    method: 'POST',
                    url: '/api/persons',
                    data: JSON.stringify($scope.newperson),
                    headers: { 'Content-Type': 'application/JSON' }
                }).
                success(function (data) {
                    //Showing Success message
                    $scope.status = "The Person Saved Successfully!!!";
                    //Loading people to the $scope
                    GetPersons();
                })
                .error(function (error) {
                    //Showing error message
                    $scope.status = 'Unable to create a person: ' + error.message;
                });
            }

            //Edit a person
            $scope.editPerson = function (pId) {
                for (i in $scope.persons) {
                    //Getting the person details from scope based on id
                    if ($scope.persons[i].Id == pId) {
                        //Assigning the Create user scope variable for editing
                        $scope.newperson = {
                            Id: $scope.persons[i].Id,
                            Name: $scope.persons[i].Name,
                            Age: $scope.persons[i].Age,
                            Gender: JSON.stringify($scope.persons[i].Gender)
                        };
                        //Hiding Save button
                        $scope.DisplaySave = false;
                        //Displaying Update button
                        $scope.DisplayUpdate = true;
                        //Clearing the Status
                        $scope.status = '';
                    }
                }
            }

            //Update a person
            $scope.updatePerson = function () {
                //Defining $http service for updating a person
                $http({
                    method: 'PUT',
                    url: '/api/persons',
                    data: JSON.stringify($scope.newperson),
                    headers: { 'Content-Type': 'application/JSON' }
                }).
                success(function (data) {
                    //Showing Success message
                    $scope.status = "The Person Updated Successfully!!!";
                    //Loading people to the $scope
                    GetPersons();
                    //Displaying save button
                    $scope.DisplaySave = true;
                    //Hiding Update button
                    $scope.DisplayUpdate = false;
                })
                .error(function (error) {
                    //Showing error message
                    $scope.status = 'Unable to update a person: ' + error.message;
                });
            }

            //Delete a person
            $scope.deletePerson = function (pId) {
                //Defining $http service for deleting a person
                $http({
                    method: 'DELETE',
                    url: '/api/persons/' + pId
                }).
                success(function (data) {
                    //Showing Success message
                    $scope.status = "The Person Deleted Successfully!!!";
                    //Loading people to the $scope
                    GetPersons();
                })
                .error(function (error) {
                    //Showing error message
                    $scope.status = 'Unable to delete a person: ' + error.message;
                });
            }

        }]);

    </script>
</head>
<body>
    <div data-ng-app="myApp">
        <div data-ng-controller="MyCtrl">
            <form>
                <h2>People Information</h2>
                <table>
                    <tr>
                        <td><b>Name</b></td>
                        <td><b>Age</b></td>
                        <td><b>Gender</b></td>
                        <td><b>Manage</b></td>
                    </tr>
                    <tr data-ng-repeat="person in persons">
                        <td>{{person.Name}}</td>
                        <td>{{person.Age}}</td>
                        <td>{{person.Gender && "Male" || "Female" }}</td>
                        <td><a href="" data-ng-click="editPerson(person.Id)">Edit</a> |
                        <a href="" data-ng-click="deletePerson(person.Id)">Delete</a>
                        </td>
                    </tr>
                </table>
                <br />
                <br />
                <h2>Save Person</h2>
                <input type="hidden" data-ng-model="newperson.Id" />
                <b>Name:</b>
                <input type="text" name="Name" id="Name" data-ng-model="newperson.Name" placeholder="Name" required />
                <b>Age:</b>
                <input type="number" name="Age" id="Age" data-ng-model="newperson.Age" placeholder="Age" required />
                <b>Gender:</b>
                <input type="radio" name="gender" data-ng-model="newperson.Gender" value="true" />
                Male
                <input type="radio" name="gender" data-ng-model="newperson.Gender" value="false" />
                Female
                <br />
                <br />
                <input type="button" value="Save" data-ng-show="DisplaySave" data-ng-click="createPerson()" />
                <input type="button" value="Update" data-ng-show="DisplayUpdate" data-ng-click="updatePerson()" />
                <br />
                <p>{{status}}</p>
            </form>
        </div>
    </div>
</body>
</html>

Now Run the application by pressing the Ctrl+F5,and Add some person details.

image1

Now,Click on Edit for a person.The data will be automatically populated for editing as shown below.

image2

Modify the person details and click on Update.

image3

Now,Let us Delete a person.

image4

Happy Coding!!!

You may also like...