In this article I will explain with an example, how to use Web API with AngularJS in ASP.Net Core MVC.
Note: For beginners in ASP.Net Core 7 and Web API, please refer my article What is Web API, why to use it and how to use it in ASP.Net Core.
 
 

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.
Note: For beginners in ASP.Net Core and Entity Framework, please refer my article ASP.Net Core 7: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework.
 
using Microsoft.EntityFrameworkCore;
 
namespace AngularJS_Web_API_Core_MVC
{
    public class DBCtx : DbContext
    {
        public DBCtx(DbContextOptions<DBCtx> options) : base(options)
        {
        }
 
        public DbSet<CustomerModel> Customers{ getset; }
    }
}
 
 

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.
Note: If you want to learn more about these directives, please refer my article Introduction to AngularJS.
 
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.
Note: If you want to learn more about ng-repeat directive, please refer my article AngularJS ng-repeat example: Populate (Bind) HTML Select DropDownList with Options.
 
The HTML Table has been also applied with the AngularJS ng-show directive and set to IsVisible.
Note: If you want to learn more about ng-show directive, please refer my article Simple AngularJS ng-show and ng-hide Tutorial with example.
 
The INPUT TextBox has been applied with an AngularJS ng-model directive which allows changes in the input field to update the model.
Note: If you want to learn more about ng-model directive, please refer my article Using ng-model directive in AngularJS.
 
The Button has been assigned with an AngularJS ng-click directive.
Note: If you want to learn more about ng-click directive, please refer my article ng-click example in AngularJS.
 
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

Using Web API with AngularJS Tutorial with example in ASP.Net Core
 
 

Downloads