In this article I will explain with an example, how to perform Select, Insert, Edit, Update and Delete operation using
Web API and
AngularJS in ASP.Net MVC.
Database
I have made use of the following table Customers with the schema as follows.
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();
}
}
Namespaces
You will need to import the following namespace.
Web API Controller
The Web API Controller consists of the following Action methods.
Action method for Selecting
Inside this Action method, all the records from the
Customers table are fetched using
Entity Framework returned to the View as a generic List collection.
Action method for Inserting
This Action method handles the call made from the
AngularJS AJAX function from the View.
Inside this Action method, the received Customer object is inserted into the
Customers table and the updated Customer object with generated
CustomerId is returned back to the
AngularJS AJAX function.
Action method for Updating
This Action method handles the call made from the
AngularJS AJAX function from the View.
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 CustomerEntities.
Finally, 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
This Action method handles the call made from the
AngularJS AJAX function from the View.
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 CustomerEntities.
Finally, 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
Inside the View, the following
AngularJS file is inherited.
1. angular.min.js
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.
The Table contains two HTML INPUT TextBox for capturing Name and Country values.
There is also a Button which will be used to add new records and it has been assigned with an
AngularJS ng-click directive.
The INPUT TextBoxes have been applied with an
AngularJS ng-model directive which allows changes in the input field to update the model.
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 determined 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 determined 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 determined 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>
</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.5.9/angular.min.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