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

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

0.00/5 (No votes)
16 Sep 2015 1  
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.

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.

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.

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.

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

<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

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.

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.

Database After Update

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

AngularJS Delete Controller

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.

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

Database after Record Deleted

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

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