In this article I will explain with an example, how to perform CRUD operation (Create, Read, Update and Delete) using Web API in ASP.Net MVC Razor using Entity Framework and AngularJS.
CRUD operation in simple terms means Select, Insert, Edit, Update and Delete operations.
Database
I have made use of the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Controller
The Controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
Web API Controller
The Web API Controller consists of the following four Action methods.
Action method for Selecting
Inside this Action method, all the records from the Customers table is returned to the View as a Generic List collection.
Action method for Inserting
Inside this Action method, the received Customer object is inserted into the Customers table and the updated Customer object with generated Customer Id is returned back to the calling AngularJS AJAX function.
Action method for Updating
Inside this Action method, the Customer object is received as parameter. The CustomerId value of the received Customer object is used to reference the Customer record in the Customer Entities.
Once the record is referenced, the values of Name and Country are updated and the changes are updated into the Customer table.
Action method for Deleting
Inside this Action method, the CustomerId value is received as parameter. The CustomerId value is used to reference the Customer record in the Customer Entities.
Once the record is referenced, the Customer record is deleted from the Customers table.
public class AjaxAPIController : ApiController
{
[Route("api/AjaxAPI/GetCustomers")]
[HttpPost]
public List<Customer> GetCustomers()
{
CustomersEntities entities = new CustomersEntities();
return entities.Customers.ToList();
}
[Route("api/AjaxAPI/InsertCustomer")]
[HttpPost]
public Customer InsertCustomer(Customer customer)
{
using (CustomersEntities entities = new CustomersEntities())
{
entities.Customers.Add(customer);
entities.SaveChanges();
}
return customer;
}
[Route("api/AjaxAPI/UpdateCustomer")]
[HttpPost]
public bool UpdateCustomer(Customer customer)
{
using (CustomersEntities entities = new CustomersEntities())
{
Customer updatedCustomer = (from c in entities.Customers
where c.CustomerId == customer.CustomerId
select c).FirstOrDefault();
updatedCustomer.Name = customer.Name;
updatedCustomer.Country = customer.Country;
entities.SaveChanges();
}
return true;
}
[Route("api/AjaxAPI/DeleteCustomer")]
[HttpPost]
public void DeleteCustomer(Customer _customer)
{
using (CustomersEntities entities = new CustomersEntities())
{
Customer customer = (from c in entities.Customers
where c.CustomerId == _customer.CustomerId
select c).FirstOrDefault();
entities.Customers.Remove(customer);
entities.SaveChanges();
}
}
}
View
The View consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML DIV consists of an HTML Table with only the Header row and another Table below it for adding new records to the database.
Display
For displaying the records, an AJAX call is made to the GetCustomers Action method of the Controller using AngularJS $http service function.
The database records are received in JSON format and are assigned to Customers JSON array.
The Customers JSON array is used to populate the HTML Table using ng-repeat directive of AngularJS.
Insert
When the Add button is clicked the Name and the Country values are fetched from their respective TextBoxes and then passed to the InsertCustomer Action method using the using AngularJS $http service function.
Once the response is received, the newly added record is pushed into the Customers JSON array.
Edit
When the Edit Button is clicked, the Index of the HTML Table row is fetched and is used to determine the Customer record being edited.
The EditMode property is set to TRUE for the Customer record which makes the TextBoxes visible for that row.
Update
When the Update Button is clicked, the Index of the HTML Table row is fetched and is used to determine the Customer record to be updated.
The values of CustomerId, Name and Country are passed to the UpdateCustomer Action method using AngularJS $http service function.
Once the response is received, the EditMode property is set to FALSE for the Customer record which hides the TextBoxes for that row.
Cancel
When the Cancel Button is clicked, the Index of the HTML Table row is fetched and is used to determine the Customer record for which the edit is being cancelled.
The EditMode property is set to FALSE for the Customer record which hides the TextBoxes for that row.
Delete
When the Delete Button is clicked, the value of the CustomerId is fetched and passed to the DeleteCustomer Action method using AngularJS $http service function.
Once the response is received the respective row is removed from the Customers JSON array.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
.table {
border: 1px solid #ccc;
border-collapse: collapse;
}
.table th {
background-color: #F7F7F7;
color: #333;
font-weight: bold;
}
.table th, .table td {
padding: 5px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div ng-app="MyApp" ng-controller="MyController">
<table id="tblCustomers" class="table" cellpadding="0" cellspacing="0">
<tr>
<th style="width:100px">Customer Id</th>
<th style="width:150px">Name</th>
<th style="width:150px">Country</th>
<th style="width:100px"></th>
</tr>
<tbody ng-repeat="m in Customers">
<tr>
<td><span>{{m.CustomerId}}</span></td>
<td>
<span ng-hide="m.EditMode">{{m.Name}}</span>
<input type="text" ng-model="m.Name" ng-show="m.EditMode"/>
</td>
<td>
<span ng-hide="m.EditMode">{{m.Country}}</span>
<input type="text" ng-model="m.Country" ng-show="m.EditMode"/>
</td>
<td>
<a class="Edit" href="javascript:;" ng-hide="m.EditMode" ng-click="Edit($index)">Edit</a>
<a class="Update" href="javascript:;" ng-show="m.EditMode" ng-click="Update($index)">Update</a>
<a class="Cancel" href="javascript:;" ng-show="m.EditMode" ng-click="Cancel($index)">Cancel</a>
<a href="javascript:;" ng-hide="m.EditMode" ng-click="Delete(m.CustomerId)">Delete</a>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 150px">
Name<br/>
<input type="text" ng-model="Name" style="width:140px"/>
</td>
<td style="width: 150px">
Country:<br/>
<input type="text" ng-model="Country" style="width:140px"/>
</td>
<td style="width: 200px">
<br/>
<input type="button" value="Add" ng-click="Add()"/>
</td>
</tr>
</table>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
//Getting records from database.
var post = $http({
method: "POST",
url: "/api/AjaxAPI/GetCustomers",
dataType: 'json',
headers: { "Content-Type": "application/json" }
});
post.success(function (data, status) {
//The received response is saved in Customers array.
$scope.Customers = data;
});
//Adding new record to database.
$scope.Add = function () {
if (typeof ($scope.Name) == "undefined" || typeof ($scope.Country) == "undefined") {
return;
}
var post = $http({
method: "POST",
url: "/api/AjaxAPI/InsertCustomer",
data: "{name: '" + $scope.Name + "', country: '" + $scope.Country + "'}",
dataType: 'json',
headers: { "Content-Type": "application/json" }
});
post.success(function (data, status) {
//The newly inserted record is inserted into the Customers array.
$scope.Customers.push(data)
});
$scope.Name = "";
$scope.Country = "";
};
//This variable is used to store the original values.
$scope.EditItem = {};
//Editing an existing record.
$scope.Edit = function (index) {
//Setting EditMode to TRUE makes the TextBoxes visible for the row.
$scope.Customers[index].EditMode = true;
//The original values are saved in the variable to handle Cancel case.
$scope.EditItem.Name = $scope.Customers[index].Name;
$scope.EditItem.Country = $scope.Customers[index].Country;
};
//Cancelling an Edit.
$scope.Cancel = function (index) {
// The original values are restored back into the Customers Array.
$scope.Customers[index].Name = $scope.EditItem.Name;
$scope.Customers[index].Country = $scope.EditItem.Country;
//Setting EditMode to FALSE hides the TextBoxes for the row.
$scope.Customers[index].EditMode = false;
$scope.EditItem = {};
};
//Updating an existing record to database.
$scope.Update = function (index) {
var customer = $scope.Customers[index];
var post = $http({
method: "POST",
url: "/api/AjaxAPI/UpdateCustomer",
data: JSON.stringify(customer),
dataType: 'json',
headers: { "Content-Type": "application/json" }
});
post.success(function (data, status) {
//Setting EditMode to FALSE hides the TextBoxes for the row.
customer.EditMode = false;
});
};
//Deleting an existing record from database.
$scope.Delete = function (customerId) {
if ($window.confirm("Do you want to delete this row?")) {
var _customer = {};
_customer.CustomerId = customerId;
var post = $http({
method: "POST",
url: "/api/AjaxAPI/DeleteCustomer",
data: JSON.stringify(_customer),
dataType: 'json',
headers: { "Content-Type": "application/json" }
});
post.success(function (data, status) {
//Remove the Deleted record from the Customers Array.
$scope.Customers = $scope.Customers.filter(function (customer) {
return customer.CustomerId !== customerId;
});
});
post.error(function (data, status) {
$window.alert(data.Message);
});
}
};
});
</script>
</body>
</html>
Screenshot
Downloads