In this article I will explain with an example, how to use
Web API with
AngularJS in ASP.Net Core MVC.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Database Context
Once the
Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
using Microsoft.EntityFrameworkCore;
namespace AngularJS_Web_API_Core_MVC
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<CustomerModel> Customers{ get; set; }
}
}
Model
The Model class consists of the following properties.
public class CustomerModel
{
[Key]
public string? CustomerId { get; set; }
public string? ContactName { get; set; }
public string? Country { get; set; }
}
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
Web API Controller
The
Web API Controller consists of the following Action method.
Action method for handling POST operation
This Action method accepts an object of CustomerModel class object.
This method is decorated with
Route attribute which defines its Route for calling the
Web API method and
HttpPost attribute which signifies that the method will accept
Post requests.
The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.
Note: A cross-site request forgery is an attack is done by sending harmful script element, malicious command, or code from the user’s browser.
Then, the records of the
Customers are fetched using
Entity Framework and are filtered using the
StartsWith function based on the value of the
ContactName property.
Finally, the records are returned as Generic List collection.
[Route("api/[controller]")]
[ApiController]
public class AjaxAPIController : ControllerBase
{
private DBCtx Context { get; }
public AjaxAPIController(DBCtx _context)
{
this.Context = _context;
}
[Route("AjaxMethod")]
[HttpPost]
[ValidateAntiForgeryToken]
public List<CustomerModel> AjaxMethod(CustomerModel model)
{
return this.Context.Customers.Where(customer => customer.ContactName.StartsWith(model.ContactName)).Take(10).ToList();
}
}
View
Inside the View, the following
AngularJS script 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 INPUT TextBox, a Submit Button and an HTML Table which will be populated from JSON array using ng-repeat directive.
The HTML Table has been also applied with the
AngularJS ng-show directive and set to
IsVisible.
The INPUT TextBox has been applied with an
AngularJS ng-model directive which allows changes in the input field to update the model.
The Button has been assigned with an
AngularJS ng-click directive.
The Anti-Forgery Token has been added to the View page using the AntiForgeryToken function of the HTML Helper class.
When the Button is clicked, the
Search function is called which will be used to call
Web API Controller.
Inside the
AngularJS controller, first the
IsVisible property is set to FALSE and the
Search function is executed.
Then, inside the
Search function, the
$http service is used to make an
AJAX call to the
Web API Controller’s method.
The $http service has following properties and event handlers.
Properties
1. method – The method type of HTTP Request i.e. GET or POST. Here it is set to POST.
2. url – URL of the
Web API Controller’s method.
3. datatype – The format of the data i.e. XML or JSON. Here it is set as JSON.
4. data – The parameters to be sent to the
Web API Controller’s method i.e. the Prefix TextBox value.
5. headers – List of headers to be specified for the HTTP Request.
Event Handlers
1. success – This event handler is triggered once the
AJAX call is successfully executed.
2. error – This event handler is triggered when the
AJAX call encounters an error.
The response from the
AJAX call is received in JSON format inside the
Success event handler of the
$http service. It is assigned to the
Customers variable.
The ng-repeat directive as the name suggests repeats the element based on the length of the collection, in this scenario it will repeat the TR element i.e. HTML Table Row.
The TBODY element of the HTML Table has been assigned with an ng-repeat directive in order to iterate through all the items of the Customers JSON array.
For each JSON object in the Customers JSON array, a TR element i.e. HTML Table Row is generated and appended into the HTML Table.
Finally, all the data is displayed in the HTML Table.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<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) {
$scope.IsVisible = false;
$scope.Search = function () {
var antiForgeryToken = document.getElementsByName("__RequestVerificationToken")[0].value;
var customer = '{"ContactName": "' + $scope.Prefix + '" }';
var post = $http({
method: "POST",
url: "/api/AjaxAPI/AjaxMethod",
dataType: 'json',
data: customer,
headers: {
"Content-Type": "application/json",
"XSRF-TOKEN": antiForgeryToken
}
});
post.success(function (data, status) {
$scope.Customers = data;
$scope.IsVisible = true;
});
post.error(function (data, status) {
$window.alert(data.Message);
});
}
});
</script>
@Html.AntiForgeryToken()
<div ng-app="MyApp" ng-controller="MyController">
Name:
<input type="text" ng-model="Prefix" />
<input type="button" value="Submit" ng-click="Search()" />
<hr />
<table cellpadding="0" cellspacing="0" ng-show="IsVisible">
<tr>
<th>Customer Id</th>
<th>Name</th>
<th>Country</th>
</tr>
<tbody ng-repeat="m in Customers">
<tr>
<td>{{m.CustomerID}}</td>
<td>{{m.ContactName}}</td>
<td>{{m.Country}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Screenshot
Downloads