Click here to Skip to main content
15,881,938 members
Articles / Web Development / HTML
Article

CRUD operation on multiple tables with AngularJS and ASP.NET MVC Part-2

Rate me:
Please Sign up or sign in to vote.
4.82/5 (12 votes)
16 Sep 2015CPOL2 min read 37.7K   1.4K   29   6
CRUD operation on multiple tables with AngularJS and ASP.NET MVC Part-2

This demo is continuation of my previous demo(http://www.codeproject.com/Articles/1029996/SPA- with-AngularJS-in-NET). Please go through pervious demo before going through this.

In the last demo I have shown how to insert and display data from database. In this demo I will show the update and delete functionalities in SPA using AngularJS. I have provided the source code for CRUD operation to download.

Last demo Comments

  • In my previous demo I have implemented Models and Calls to server in one controller.
  • Since all the code is in a controller, so one of the comment was it is not good practice and I agree.
  • My previous demo is for starters only so I did not do any separation because it may confuse them.

AngularJS Code Changes

  • In this demo I have developed AngularJS code completely from scratch.
  • I have added AddController, DeleteController, EditController, Service and myApp JavaScript files. Check the below image.

Image 1

AngularJS Code

myApp.js Code

Below we only have client side routing and angular module and I am not going to explain these concepts as I have already done so in my previous demo. So just copy below code in your JS file.

JavaScript
var app = angular.module('App', ['AngularDemo.EmpAddController',
                       'AngularDemo.AddressController',
                       'AngularDemo.DeleteController'
])
 
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
 
    $routeProvider.when('/', {
        templateUrl: '/Home/AddEmployee',
        controller: 'EmpAddCtrl',
    });
    $routeProvider.when('/Edit', {
        templateUrl: '/Home/EditEmployee',
        controller: 'EditCtrl'
    });
    $routeProvider.when('/Delete', {
        templateUrl: '/Home/DeleteEmployee',
        controller: 'DeleteCtrl'
    });
    $routeProvider.otherwise({
        redirectTo: '/'
    });
    // Specify HTML5 mode (using the History APIs) or HashBang syntax.
    $locationProvider.html5Mode(false).hashPrefix('!');
 
}]);

Service.js Code

  • Only one object is created for app and it is singleton object.
  • Services are used to share data and functions across in your app.
  • In this demo all calls to server s are done from " CRUDService ".

For examples if you wanted to delete row, so call is made from DeleteController.js ($scope.DeleteByID) which invokes DeleteEmployee method in CRUDService class.

JavaScript
app.service("CRUDService", function ($http) {
    this.getAllEmployeeInfo = function () {
        return $http.get('/Home/ShowEmpList');
    };
 
    this.AddEmployee = function (EmployeeViewModel) {
        var ServerData = $http({
            method: "Post",
            url: "/Home/AddEmpDetails",
            data: JSON.stringify({ EmployeeViewModelClient: EmployeeViewModel }),
            dataType: 'json',
            //contentType: 'application/json',
        });
        return ServerData;
    }
 
    this.EditEmployee = function (EmployeeID) {
        var ServerData = $http({
            method: "Post",
            url: "/Home/GetEmployeeById",
            data: JSON.stringify({ EmpID: EmployeeID }),
            dataType: 'json',
            //contentType: 'application/json',
        });
        return ServerData;
    }
 
    this.UpdateEmployee = function (EmployeeViewModel) {
        var ServerData = $http({
            method: "Post",
            url: "/Home/UpdateEmployee",
            data: JSON.stringify({ EmployeeViewModelClient: EmployeeViewModel }),
            dataType: 'json',
            //contentType: 'application/json',
        });
        return ServerData;
    }
 
    this.DeleteEmployee = function (EmployeeID) {
        var ServerData = $http({
            method: "Post",
            url: "/Home/DeleteByID",
            data: JSON.stringify({ EmpID: EmployeeID }),
            dataType: 'json',
            //contentType: 'application/json',
        });
        return ServerData;
    }
});

AngularJS Edit controller

Create edit controller file with whatever name you wanted and copy below file in it.

JavaScript
angular.module('AngularDemo.AddressController', ['ngRoute'])
app.controller('EditCtrl', function ($scope, CRUDService) {
 
    var GetAllData = CRUDService.getAllEmployeeInfo();
    GetAllData.then(function (data) {
        $scope.EmpAddressList = data.data;
    })
 
    $scope.EmpDetailsModel =
     {
         EmpID: '',
         EmpName: '',
         EmpPhone: ''
     };
 
    $scope.EmpAddressModel =
    {
        Address1: '',
        Address2: '',
        Address3: ''
    };
 
    $scope.EmployeeViewModel = {
        empDetailModel: $scope.EmpDetailsModel,
        empAddressModel: $scope.EmpAddressModel
    };
 
    $scope.EditEmployee = function (EmployeeID) {
        var EditedEmployee = CRUDService.EditEmployee(EmployeeID);
        EditedEmployee.then(function (Emp) {
            $scope.EmpDetailsModel.EmpID = Emp.data[0].empDetailModel.EmpID;
            $scope.EmpDetailsModel.EmpName = Emp.data[0].empDetailModel.EmpName;
            $scope.EmpDetailsModel.EmpPhone = Emp.data[0].empDetailModel.EmpPhone;
            $scope.EmpAddressModel.Address1 = Emp.data[0].empAddressModel.Address1
            $scope.EmpAddressModel.Address2 = Emp.data[0].empAddressModel.Address2;
            $scope.EmpAddressModel.Address3 = Emp.data[0].empAddressModel.Address3;
            $scope.$apply();
        })
    };
 
    $scope.UpdateEmployee = function () {
        var UpdatedEmployee = CRUDService.UpdateEmployee($scope.EmployeeViewModel);
        UpdatedEmployee.then(function (Emp) {
            $scope.EmpAddressList = Emp.data;
            $scope.$apply();
        })
    };
);

Edit/Update View HTML

HTML
<div style="width: 50%; margin: 50px auto;">
 
    <table id="EmployeeDetails">
        <tr>
            <td>
                <strong>Employee Name:</strong>
            </td>
            <td>
                <input type="text" class="form-control" ng-model="EmpDetailsModel.EmpName" placeholder="Employee Name"/>
            </td>
        </tr>
        <tr>
            <td>
                <strong>Employee Phone:</strong>
 
            </td>
            <td>
                <input type="text" class="form-control" ng-model="EmpDetailsModel.EmpPhone" placeholder="Employee Phone" />
            </td>
        </tr>
        <tr>
            <td>
                <strong>Address 1:</strong>
 
            </td>
            <td>
                <input type="text" class="form-control" ng-model="EmpAddressModel.Address1" placeholder="Address 1" />
            </td>
        </tr>
        <tr>
            <td>
                <strong>Address 2:</strong>
 
            </td>
            <td>
                <input type="text" class="form-control" ng-model="EmpAddressModel.Address2" placeholder="Address 2" />
            </td>
        </tr>
 
        <tr>
            <td>
                <strong>Address 3:</strong>
 
            </td>
            <td>
                <input type="text" class="form-control" ng-model="EmpAddressModel.Address3" placeholder="Address 3" />
            </td>
        </tr>
        <br />
        <tr>
            <td>&nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td>
                <button type="button" ng-click="UpdateEmployee();" class="btn btn-primary">Update</button>
            </td>
        </tr>
 
    </table>
</div>
 
<hr style="color: black" />
 
<div style="width: 50%; margin: 50px auto;">
    <div class="panel panel-default">
        <!-- Default panel contents -->
        <div class="panel-heading"><b>Employee Details </b></div>
        <div class="table-responsive">
            <table id="EmployeeTable" class="table table-striped table-bordered table-hover table-condensed">
                <thead>
                    <tr>
                        <th>Employee ID</th>
                        <th>Employee Name</th>
                        <th>Employee Phone</th>
                        <th>Employee Address1</th>
                        <th>Employee Address2</th>
                        <th>Employee Address3</th>
                    </tr>
                </thead>
                <tbody>
                    <tr data-ng-repeat="Emp in EmpAddressList">
 
                        <td>{{Emp.empDetailModel.EmpID}}</td>
                        <td>{{Emp.empDetailModel.EmpName}}</td>
                        <td>{{Emp.empDetailModel.EmpPhone}}</td>
                        <td>{{Emp.empAddressModel.Address1}}</td>
                        <td>{{Emp.empAddressModel.Address2}}</td>
                        <td>{{Emp.empAddressModel.Address3}}</td>
                        <td><span ng-click="EditEmployee(Emp.empDetailModel.EmpID)" class="btn btn-primary">Edit</span></td>
                    </tr>
 
                    @*<tr ng-if="states.NewRow">*@
                    <tr ng-if="EmpAddressList.length == 0">
                        <td class="text-center" colspan="4">There are no Employee details to display
                        </td>
                    </tr>
                </tbody>
            </table>
 
        </div>
    </div>
</div>

Edit/Update Output

Image 2

When user clicks on Edit/Update, it populates all the records with corresponding edit button for each row, above is the screen shot of it. When user clicks on edit button respective data is populated in text boxes.

Image 3

After changing values of the employee and clicked on update button, values are passed to controller action, below are the two screen shots of the two models EmpDetailsModel and EmpAddressModel with data passed to action.

Image 4

Image 5

Database After Update

Before update all the values of for EmpID 177 was 1 and after update the values are 5.

Image 6

AngularJS Delete Controller

JavaScript
angular.module('AngularDemo.DeleteController', ['ngRoute'])
app.controller('DeleteCtrl', function ($scope, CRUDService) {
    $scope.EmpAddressList = {};
 
    var GetAllData = CRUDService.getAllEmployeeInfo();
    GetAllData.then(function (data) {
        $scope.EmpAddressList = data.data;
    })
 
    $scope.DeleteByID = function (EmployeeID) {
        //debugger;
        var DeletedEmployee = CRUDService.DeleteEmployee(EmployeeID);
        DeletedEmployee.then(function (Emp) {
            $scope.EmpAddressList = Emp.data;
        })
    }
});

When user clicks on delete from menu, it populates all the records with corresponding delete button for each row, below is the screen shot of it.

Image 7

Delete View HTML

HTML
<div style="width: 50%; margin: 50px auto;">
    <div class="panel panel-default">
        <!-- Default panel contents -->
        <div class="panel-heading"><b>Employee Details </b></div>
        <div class="table-responsive">
            <table id="EmployeeTable" class="table table-striped table-bordered table-hover table-condensed">
                <thead>
                    <tr>
                        <th>Employee ID</th>
                        <th>Employee Name</th>
                        <th>Employee Phone</th>
                        <th>Employee Address1</th>
                        <th>Employee Address2</th>
                        <th>Employee Address3</th>
                    </tr>
                </thead>
                <tbody>
                    <tr data-ng-repeat="Emp in EmpAddressList">
                        <td>{{Emp.empDetailModel.EmpID}}</td>
                        <td>{{Emp.empDetailModel.EmpName}}</td>
                        <td>{{Emp.empDetailModel.EmpPhone}}</td>
                        <td>{{Emp.empAddressModel.Address1}}</td>
                        <td>{{Emp.empAddressModel.Address2}}</td>
                        <td>{{Emp.empAddressModel.Address3}}</td>
                        <td><button type="button" ng-click="DeleteByID(Emp.empDetailModel.EmpID)" class="btn btn-primary">Delete</button></td>
                    </tr>
                    <tr ng-if="EmpAddressList.length == 0">
                        <td class="text-center" colspan="4">There are no Employee details to display
                        </td>
                    </tr>
                </tbody>
            </table>
 
        </div>
    </div>
</div>

When user clicks on delete button corresponding records is deleted.

Image 8

Database after Record Deleted

Image 9

Note: Please let me know if you have any questions on this demo or any other suggestions for better implementation.

License

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


Written By
Software Developer (Senior)
India India
Currently working for Visionet Systems. Love to work in web technologies.

Comments and Discussions

 
QuestionA Bug Pin
Member 1176032626-Dec-16 8:56
Member 1176032626-Dec-16 8:56 
QuestionA few questions for this excellent example Pin
Member 1176032628-Nov-16 19:20
Member 1176032628-Nov-16 19:20 
Question$scope.EmpAddressList.push is not a function Pin
enavuio24-Feb-16 15:12
enavuio24-Feb-16 15:12 
AnswerRe: $scope.EmpAddressList.push is not a function Pin
Kranthi Kumar Pothireddy15-Mar-16 23:10
Kranthi Kumar Pothireddy15-Mar-16 23:10 
QuestionPretty good Pin
Troy Bryant22-Jan-16 4:31
Troy Bryant22-Jan-16 4:31 
AnswerRe: Pretty good Pin
Member 1176032628-Nov-16 19:13
Member 1176032628-Nov-16 19:13 

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.