In this article I will explain with an example, how to perform select, insert, edit, update and delete operations using
AngularJS in ASP.Net MVC.
Entity Framework will be used to perform CRUD operation i.e. Select, Insert, Edit, Update and Delete operations 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.
Creating an Entity Data Model
The very first step is to create an ASP.Net MVC Application and connect it to the
Northwind database using
Entity Framework.
Following is the Entity Data Model of the
Customers Table of the
SQL Server database which will be used later in this project.
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for Selecting
Inside this Action method, all the records from the
Customers Table are fetched using
Entity Framework and 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 Customers 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, the referenced record is deleted and changes are updated into the Customers Table.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult GetCustomers()
{
CustomersEntities entities = new CustomersEntities();
return Json(entities.Customers);
}
[HttpPost]
public JsonResult InsertCustomer(Customer customer)
{
using (CustomersEntities entities = new CustomersEntities())
{
entities.Customers.Add(customer);
entities.SaveChanges();
}
return Json(customer);
}
[HttpPost]
public ActionResult 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 new EmptyResult();
}
[HttpPost]
public ActionResult DeleteCustomer(int customerId)
{
using (CustomersEntities entities = new CustomersEntities())
{
Customer customer = (from c in entities.Customers
where c.CustomerId == customerId
select c).FirstOrDefault();
entities.Customers.Remove(customer);
entities.SaveChanges();
}
return new EmptyResult();
}
}
View
HTML Markup
Inside the View, the following JS file is inherited.
1. angular.min.js
The HTML of the View consists of following controls:
div – For applying
ng-app and
ng-controller AngularJS directives.
TextBox – For capturing Name and Country values.
The HTML DIV consists of an HTML Table for displaying records and another Table below it for adding new records to the database.
The HTML Table for displaying records consists of HTML SPAN elements and HTML INPUT TextBoxes to display and edit the existing records.
The INPUT TextBoxes inside the Table for displaying records have been assigned with the following
AngularJS directive.
ng-model – For updating the model.
ng-show – For hiding and showing the element.
It also consists of Anchor elements which will be used to edit, update, cancel and delete the records.
The HTML Anchor elements have been assigned with the following
AngularJS directives.
ng-click – Trigger when user clicks the Button.
ng-hide – For hiding the elements.
ng-show – For showing the elements.
Button – For adding records.
The HTML INPUT Button has been assigned with the following
AngularJS directive.
ng-click – Trigger when user clicks the Button.
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 Button is clicked, the Add function is executed.
Inside this
Add function, 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" 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