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
- USE [master]
- GO
- /****** Object: Database [CustomerDB] Script Date: 9/21/2016 7:42:43 AM ******/
- CREATE DATABASE [CustomerDB]
- CONTAINMENT = NONE
- ON PRIMARY
- ( NAME = N'CustomerDB', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\CustomerDB.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
- LOG ON
- ( 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%)
- GO
- ALTER DATABASE [CustomerDB] SET COMPATIBILITY_LEVEL = 110
- GO
- IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
- begin
- EXEC [CustomerDB].[dbo].[sp_fulltext_database] @action = 'enable'
- end
- GO
- ALTER DATABASE [CustomerDB] SET ANSI_NULL_DEFAULT OFF
- GO
- ALTER DATABASE [CustomerDB] SET ANSI_NULLS OFF
- GO
- ALTER DATABASE [CustomerDB] SET ANSI_PADDING OFF
- GO
- ALTER DATABASE [CustomerDB] SET ANSI_WARNINGS OFF
- GO
- ALTER DATABASE [CustomerDB] SET ARITHABORT OFF
- GO
- ALTER DATABASE [CustomerDB] SET AUTO_CLOSE OFF
- GO
- ALTER DATABASE [CustomerDB] SET AUTO_CREATE_STATISTICS ON
- GO
- ALTER DATABASE [CustomerDB] SET AUTO_SHRINK OFF
- GO
- ALTER DATABASE [CustomerDB] SET AUTO_UPDATE_STATISTICS ON
- GO
- ALTER DATABASE [CustomerDB] SET CURSOR_CLOSE_ON_COMMIT OFF
- GO
- ALTER DATABASE [CustomerDB] SET CURSOR_DEFAULT GLOBAL
- GO
- ALTER DATABASE [CustomerDB] SET CONCAT_NULL_YIELDS_NULL OFF
- GO
- ALTER DATABASE [CustomerDB] SET NUMERIC_ROUNDABORT OFF
- GO
- ALTER DATABASE [CustomerDB] SET QUOTED_IDENTIFIER OFF
- GO
- ALTER DATABASE [CustomerDB] SET RECURSIVE_TRIGGERS OFF
- GO
- ALTER DATABASE [CustomerDB] SET DISABLE_BROKER
- GO
- ALTER DATABASE [CustomerDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
- GO
- ALTER DATABASE [CustomerDB] SET DATE_CORRELATION_OPTIMIZATION OFF
- GO
- ALTER DATABASE [CustomerDB] SET TRUSTWORTHY OFF
- GO
- ALTER DATABASE [CustomerDB] SET ALLOW_SNAPSHOT_ISOLATION OFF
- GO
- ALTER DATABASE [CustomerDB] SET PARAMETERIZATION SIMPLE
- GO
- ALTER DATABASE [CustomerDB] SET READ_COMMITTED_SNAPSHOT OFF
- GO
- ALTER DATABASE [CustomerDB] SET HONOR_BROKER_PRIORITY OFF
- GO
- ALTER DATABASE [CustomerDB] SET RECOVERY SIMPLE
- GO
- ALTER DATABASE [CustomerDB] SET MULTI_USER
- GO
- ALTER DATABASE [CustomerDB] SET PAGE_VERIFY CHECKSUM
- GO
- ALTER DATABASE [CustomerDB] SET DB_CHAINING OFF
- GO
- ALTER DATABASE [CustomerDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
- GO
- ALTER DATABASE [CustomerDB] SET TARGET_RECOVERY_TIME = 0 SECONDS
- GO
- ALTER DATABASE [CustomerDB] SET READ_WRITE
- GO
Create Table - USE[CustomerDB]
- GO
- /****** Object: Table [dbo].[Customers] Script Date: 9/21/2016 7:43:07 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- SET ANSI_PADDING ON
- GO
- CREATE TABLE[dbo].[Customers](
- [CustomerID][int] NOT NULL, [CustomerName][varchar](50) NULL, [CustomerEmail][varchar](50) NULL, [CustomerZipCode][int] NULL, [CustomerCountry][varchar](50) NULL, [CustomerCity][varchar](50) NULL,
- CONSTRAINT[PK_Customers] PRIMARY KEY CLUSTERED(
- [CustomerID] 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
- SET ANSI_PADDING OFF
- GO
After creating the table, you can add some records as shown below.
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.
Next, new window will pop up for selecting the template. Choose Web API and click OK.
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.
In this level, we are going to choose EF Designer from database, as shown below.
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.
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.
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. Enter Controller name (‘CustomerController’).
CustomerController.cs - using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using DeleteMultipleRowsAPI;
- namespace DeleteMultipleRowsAPI.Controllers {
- public class CustomerController: ApiController {
- //DbContext
- private CustomerDBEntities context = new CustomerDBEntities();
-
- //Get Customer List
- [HttpGet]
- public IEnumerable < Customer > GetAllCustomers() {
- var data = context.Customers.ToList();
- return data;
- }
-
- //Delete Customers
- [HttpPost]
- public HttpResponseMessage DeleteCustomers(int[] itemsSelected) {
-
- try {
- if (itemsSelected == null) {
- return Request.CreateResponse(HttpStatusCode.BadRequest, "Error null !");
- } else {
- for (int i = 0; i < itemsSelected.Length; i++) {
- var customer = context.Customers.Find(itemsSelected[i]);
-
- context.Customers.Remove(customer);
-
- }
- context.SaveChanges();
- return Request.CreateResponse(HttpStatusCode.OK, "Success !");
- }
-
- } catch (Exception ex) {
-
- return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
- }
- }
- }
- }
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.
For doing this, right click on
AppCustomers folder
> Add > JavaScript file.
AppCustomer.js - var app = angular.module('myApp', ['ngRoute']);
- app.config(['$routeProvider', function($routeProvider) {
- $routeProvider.when('/CustomerGrid', {
- templateUrl: '/AppCustomers/Views/CustomerGrid.html',
- controller: 'CustomerController'
- }).otherwise({
- controller: 'CustomerController'
- });
- }]);
CustomerController.js
- app.controller('CustomerController', function($scope, $http, $window) {
- $scope.CustomerList = [];
- $http.get('api/Customer/GetAllCustomers').success(function(data) {
- $scope.CustomerList = data;
- }).error(function() {
- console.log('Something Wrong');
- });
- $scope.DeleteCustomer = function(list) {
- var itemList = [];
- angular.forEach(list, function(value, key) {
- if (list[key].selected) {
- itemList.push(list[key].selected);
- }
- });
- //console.log(itemList.length);
- $http.post("api/Customer/DeleteCustomers", itemList).success(function(data) {
- $window.alert(data);
- }).error(function(msg) {
- console.log(msg);
- });
- }
- });
Create html page
Now, we are going to add HTML file. For this right click on
Views folder
> Add > HTML Page.
CustomerGrid.html - <a href="" class="btn btn-primary" ng-click="DeleteCustomer(CustomerList)">Delete Multiple Rows selected</a>
- <br /><br />
- <div class="table-responsive">
- <table id="mytable" class="table table-bordred table-striped">
- <thead>
- <th></th>
- <th>Customer ID</th>
- <th>Customer Name</th>
- <th>Customer Email</th>
- <th>Customer ZipCode</th>
- <th>Customer Country</th>
- <th>Customer City</th>
- </thead>
- <tbody>
- <tr ng-repeat="item in CustomerList">
- <td><input type="checkbox" id="check1" ng-true-value="{{item.CustomerID}}" ng-false-value="''" ng-model="item.selected" /></td>
- <td>{{item.CustomerID}}</td>
- <td>{{item.CustomerName}}</td>
- <td>{{item.CustomerEmail}}</td>
- <td>{{item.CustomerZipCode}}</td>
- <td>{{item.CustomerCountry}}</td>
- <td>{{item.CustomerCity}}</td>
- </tr>
- </tbody>
- </table>
- </div>
Note - Don’t forget to call the following libraries inside
Layout.cshtml. -
- <
- script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js" > < /script> <
- script src = "https://code.angularjs.org/1.4.7/angular-route.js" > < /script>
-
- <
- script src = "~/AppCustomers/AppCustomer.js" > < /script>
-
- <
- script src = "~/AppCustomers/CustomerController.js" > < /script>
Output