Delete Multiple Records With AngularJS Using MVC 5

Introduction

In this article, we will learn how we can delete multiple records from Grid data, by using Web API 2, AngularJS, and Entity Framework.

Prerequisites

As I said earlier, we are going to use MVC application with AngularJS. For this, you must have Visual Studio 2015 (.NET Framework 4.5.2) and SQL Server.

SQL Database part

Here, you will find the scripts to create database and table.

Create Database

  1. USE [master]  
  2. GO  
  3. /****** Object: Database [CustomerDB] Script Date: 9/21/2016 7:42:43 AM ******/  
  4. CREATE DATABASE [CustomerDB]  
  5. CONTAINMENT = NONE  
  6. ON PRIMARY   
  7. NAME = N'CustomerDB'FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\CustomerDB.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITEDFILEGROWTH = 1024KB )  
  8. LOG ON   
  9. NAME = N'CustomerDB_log'FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\CustomerDB_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  10. GO  
  11. ALTER DATABASE [CustomerDB] SET COMPATIBILITY_LEVEL = 110  
  12. GO  
  13. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  14. begin  
  15. EXEC [CustomerDB].[dbo].[sp_fulltext_database] @action = 'enable'  
  16. end  
  17. GO  
  18. ALTER DATABASE [CustomerDB] SET ANSI_NULL_DEFAULT OFF   
  19. GO  
  20. ALTER DATABASE [CustomerDB] SET ANSI_NULLS OFF   
  21. GO  
  22. ALTER DATABASE [CustomerDB] SET ANSI_PADDING OFF   
  23. GO  
  24. ALTER DATABASE [CustomerDB] SET ANSI_WARNINGS OFF   
  25. GO  
  26. ALTER DATABASE [CustomerDB] SET ARITHABORT OFF   
  27. GO  
  28. ALTER DATABASE [CustomerDB] SET AUTO_CLOSE OFF   
  29. GO  
  30. ALTER DATABASE [CustomerDB] SET AUTO_CREATE_STATISTICS ON   
  31. GO  
  32. ALTER DATABASE [CustomerDB] SET AUTO_SHRINK OFF   
  33. GO  
  34. ALTER DATABASE [CustomerDB] SET AUTO_UPDATE_STATISTICS ON   
  35. GO  
  36. ALTER DATABASE [CustomerDB] SET CURSOR_CLOSE_ON_COMMIT OFF   
  37. GO  
  38. ALTER DATABASE [CustomerDB] SET CURSOR_DEFAULT GLOBAL   
  39. GO  
  40. ALTER DATABASE [CustomerDB] SET CONCAT_NULL_YIELDS_NULL OFF   
  41. GO  
  42. ALTER DATABASE [CustomerDB] SET NUMERIC_ROUNDABORT OFF   
  43. GO  
  44. ALTER DATABASE [CustomerDB] SET QUOTED_IDENTIFIER OFF   
  45. GO  
  46. ALTER DATABASE [CustomerDB] SET RECURSIVE_TRIGGERS OFF   
  47. GO  
  48. ALTER DATABASE [CustomerDB] SET DISABLE_BROKER   
  49. GO  
  50. ALTER DATABASE [CustomerDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF   
  51. GO  
  52. ALTER DATABASE [CustomerDB] SET DATE_CORRELATION_OPTIMIZATION OFF   
  53. GO  
  54. ALTER DATABASE [CustomerDB] SET TRUSTWORTHY OFF   
  55. GO  
  56. ALTER DATABASE [CustomerDB] SET ALLOW_SNAPSHOT_ISOLATION OFF   
  57. GO  
  58. ALTER DATABASE [CustomerDB] SET PARAMETERIZATION SIMPLE   
  59. GO  
  60. ALTER DATABASE [CustomerDB] SET READ_COMMITTED_SNAPSHOT OFF   
  61. GO  
  62. ALTER DATABASE [CustomerDB] SET HONOR_BROKER_PRIORITY OFF   
  63. GO  
  64. ALTER DATABASE [CustomerDB] SET RECOVERY SIMPLE   
  65. GO  
  66. ALTER DATABASE [CustomerDB] SET MULTI_USER   
  67. GO  
  68. ALTER DATABASE [CustomerDB] SET PAGE_VERIFY CHECKSUM   
  69. GO  
  70. ALTER DATABASE [CustomerDB] SET DB_CHAINING OFF   
  71. GO  
  72. ALTER DATABASE [CustomerDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )   
  73. GO  
  74. ALTER DATABASE [CustomerDB] SET TARGET_RECOVERY_TIME = 0 SECONDS   
  75. GO  
  76. ALTER DATABASE [CustomerDB] SET READ_WRITE   
  77. GO  
Create Table
  1. USE[CustomerDB]  
  2. GO  
  3. /****** Object: Table [dbo].[Customers] Script Date: 9/21/2016 7:43:07 AM ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. SET ANSI_PADDING ON  
  9. GO  
  10. CREATE TABLE[dbo].[Customers](  
  11.     [CustomerID][int] NOT NULL, [CustomerName][varchar](50) NULL, [CustomerEmail][varchar](50) NULL, [CustomerZipCode][int] NULL, [CustomerCountry][varchar](50) NULL, [CustomerCity][varchar](50) NULL,  
  12.     CONSTRAINT[PK_Customers] PRIMARY KEY CLUSTERED(  
  13.         [CustomerID] ASC  
  14.     ) WITH(PAD_INDEX = OFFSTATISTICS_NORECOMPUTE = OFFIGNORE_DUP_KEY = OFFALLOW_ROW_LOCKS = ONALLOW_PAGE_LOCKS = ON) ON[PRIMARY]  
  15. ) ON[PRIMARY]  
  16. GO  
  17. SET ANSI_PADDING OFF  
  18. GO  
After creating the table, you can add some records as shown below.

table

Create your MVC application

Open Visual Studio and select File, click New Project.
 
The "New Project" window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.

table

Next, new window will pop up for selecting the template. Choose Web API and click OK.

table

After creating our project, we are going to add ADO.NET Entity Data Model.

Adding ADO.NET Entity Data Model

In order to add ADO.NET Entity Data Model, right click on the project name, click Add > Add New Item. New dialog box will pop up. Inside Visual C#, select Data >> ADO.NET Entity Data Model. Enter a name for your Dbcontext model as DbContextCustomer. Finally, click Add.

DbContextCustomer

In this level, we are going to choose EF Designer from database, as shown  below.

DbContextCustomer

In this snapshot given below, we need to choose data connection which should be used to connect to the database. If the connection doesn’t exist, I will suggest you click on New connection button for creating the new one.

button for creating

After clicking on Next button, the Entity Data Model Wizard will pop up for choosing object which we want to use. In this example, we are going to choose customers table and click Finish button. Finally, we see that EDMX model generates customer class.

customer

Create a Controller

Now, we are going to create a Controller. Right click on the Controllers folder > Add > Controller> select Web API 2 Controller – Empty > click Add.

create a controller

Enter Controller name (‘CustomerController’).

create a controller

CustomerController.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using DeleteMultipleRowsAPI;  
  8. namespace DeleteMultipleRowsAPI.Controllers {  
  9.     public class CustomerController: ApiController {  
  10.         //DbContext  
  11.         private CustomerDBEntities context = new CustomerDBEntities();  
  12.   
  13.         //Get Customer List  
  14.         [HttpGet]  
  15.         public IEnumerable < Customer > GetAllCustomers() {  
  16.             var data = context.Customers.ToList();  
  17.             return data;  
  18.         }  
  19.   
  20.         //Delete Customers   
  21.         [HttpPost]  
  22.         public HttpResponseMessage DeleteCustomers(int[] itemsSelected) {  
  23.   
  24.             try {  
  25.                 if (itemsSelected == null) {  
  26.                     return Request.CreateResponse(HttpStatusCode.BadRequest, "Error null !");  
  27.                 } else {  
  28.                     for (int i = 0; i < itemsSelected.Length; i++) {  
  29.                         var customer = context.Customers.Find(itemsSelected[i]);  
  30.   
  31.                         context.Customers.Remove(customer);  
  32.   
  33.                     }  
  34.                     context.SaveChanges();  
  35.                     return Request.CreateResponse(HttpStatusCode.OK, "Success !");  
  36.                 }  
  37.   
  38.             } catch (Exception ex) {  
  39.   
  40.                 return Request.CreateResponse(HttpStatusCode.BadRequest, ex);  
  41.             }  
  42.         }  
  43.     }  
  44. }  
After creating our Controller, it’s time to implement respectively two functions. GetAllCustomers() function which selects all the data from customers table, and Delete customers() function that takes an array of integer as parameter and performs the deletion of all records based on the array given as parameter.

AngularJS Part

Now, we are going to create two JS files, AppCustomer.js and CustomerController.js respectively.

AppCustomers

For doing this, right click on AppCustomers folder > Add > JavaScript file.

AppCustomers

AppCustomer.js
  1. var app = angular.module('myApp', ['ngRoute']);  
  2. app.config(['$routeProvider', function($routeProvider) {  
  3.     $routeProvider.when('/CustomerGrid', {  
  4.         templateUrl: '/AppCustomers/Views/CustomerGrid.html',  
  5.         controller: 'CustomerController'  
  6.     }).otherwise({  
  7.         controller: 'CustomerController'  
  8.     });  
  9. }]);  
CustomerController.js
  1. app.controller('CustomerController', function($scope, $http, $window) {  
  2.     $scope.CustomerList = [];  
  3.     $http.get('api/Customer/GetAllCustomers').success(function(data) {  
  4.         $scope.CustomerList = data;  
  5.     }).error(function() {  
  6.         console.log('Something Wrong');  
  7.     });  
  8.     $scope.DeleteCustomer = function(list) {  
  9.         var itemList = [];  
  10.         angular.forEach(list, function(value, key) {  
  11.             if (list[key].selected) {  
  12.                 itemList.push(list[key].selected);  
  13.             }  
  14.         });  
  15.         //console.log(itemList.length);  
  16.         $http.post("api/Customer/DeleteCustomers", itemList).success(function(data) {  
  17.             $window.alert(data);  
  18.         }).error(function(msg) {  
  19.             console.log(msg);  
  20.         });  
  21.     }  
  22. });  
Create html page

Now, we are going to add HTML file. For this right click on Views folder > Add > HTML Page.

Create html page

CustomerGrid.html
  1. <a href="" class="btn btn-primary" ng-click="DeleteCustomer(CustomerList)">Delete Multiple Rows selected</a>  
  2. <br /><br />  
  3. <div class="table-responsive">  
  4.     <table id="mytable" class="table table-bordred table-striped">  
  5.         <thead>  
  6.             <th></th>  
  7.             <th>Customer ID</th>  
  8.             <th>Customer Name</th>  
  9.             <th>Customer Email</th>  
  10.             <th>Customer ZipCode</th>  
  11.             <th>Customer Country</th>  
  12.             <th>Customer City</th>  
  13.         </thead>  
  14.         <tbody>  
  15.             <tr ng-repeat="item in CustomerList">  
  16.                 <td><input type="checkbox" id="check1" ng-true-value="{{item.CustomerID}}" ng-false-value="''" ng-model="item.selected" /></td>  
  17.                 <td>{{item.CustomerID}}</td>  
  18.                 <td>{{item.CustomerName}}</td>  
  19.                 <td>{{item.CustomerEmail}}</td>  
  20.                 <td>{{item.CustomerZipCode}}</td>  
  21.                 <td>{{item.CustomerCountry}}</td>  
  22.                 <td>{{item.CustomerCity}}</td>  
  23.             </tr>  
  24.         </tbody>  
  25.     </table>  
  26. </div>  
Note - Don’t forget to call the following libraries inside Layout.cshtml.
  1. <!-- AngularJS Libraries-->  
  2. <  
  3. script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js" > < /script> <  
  4.     script src = "https://code.angularjs.org/1.4.7/angular-route.js" > < /script>  
  5.     <!--AppCustomer.js-->  
  6.     <  
  7.     script src = "~/AppCustomers/AppCustomer.js" > < /script>  
  8.     <!--CustomerController.js-->  
  9.     <  
  10.     script src = "~/AppCustomers/CustomerController.js" > < /script>  
Output

Output


Similar Articles