In this article I will explain with an example, how to check Email Address availability i.e. check whether Email Address exists in database or not using AngularJS and Entity Framework in ASP.Net Core Razor Pages.
This article will illustrate how to check Email Address availability in database on Registration Form by making AJAX call to database using AngularJS and Entity Framework in ASP.Net Core Razor Pages.
Note: For beginners in ASP.Net Core Razor Pages, please refer my article ASP.Net Core Razor Pages: Hello World Tutorial with Sample Program example.
 
 
Database
I have made use of the following table Users with the schema as follows.
ASP.Net Core Razor Pages: Check Email Availability (Exists) in Database using AngularJS
 
I have already inserted few records in the table.
ASP.Net Core Razor Pages: Check Email Availability (Exists) in Database using AngularJS
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Configuring the Anti-Forgery Token and JSON Serializer setting
The first step is to configure the Anti-Forgery Token and JSON Serializer settings in the Startup.cs file.
1. Open the Startup.cs class from the Solution Explorer window.
ASP.Net Core Razor Pages: Check Email Availability (Exists) in Database using AngularJS
 
2. Add the following namespaces.
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Serialization;
 
3. Then inside the ConfigureServices method, you will have to add the following code which will instruct the program to:
1. Add MVC Services for Razor Pages.
2. Use Newtonsoft JSON for serialization.
3. Add Anti-Forgery Token with specific name to the Form.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
    services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
}
 
 
 
Model
The Model class consists of the following properties.
public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
}
 
 
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 Razor Pages and Entity Framework, please refer my ASP.Net Core Razor Pages: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework with ASP.Net Core Razor Pages.
 
using Check_Email_Angular_Razor_Core.Models;
using Microsoft.EntityFrameworkCore;
 
namespace Check_Email_Angular_Razor_Core
{
    public class DBCtx : DbContext
    {
        public DBCtx(DbContextOptions<DBCtx> options) : base(options)
        {
        }
 
        public DbSet<User> Users { get; set; }
    }
}
 
 
Razor PageModel (Code-Behind)
The PageModel consists of two Handler methods.
Handler method for handling GET operation
This Handler method handles the GET calls, for this particular example it is not required and hence left empty.
 
Handler method for handling AngularJS AJAX operation
This Handler method handles the AJAX call made from the AngularJS $http service in the Razor Page.
Attributes
ValidateAntiForgeryToken: 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.
 
The object of User class is received as parameter and the Email property holds the value of the TextBox sent from the AngularJS $http service.
The value of the Email Address is compared with the records from the Users table fetched using Entity Framework with the help of Lambda expression.
If the Email Address does not exists in the Users table, then True value is returned and if it exists then False value is returned.
Note: The following Handler method handles POST call and will return JSON object and hence the return type is set to JsonResult. For more details please refer Using jQuery AJAX in ASP.Net Core Razor Pages.
 
public class IndexModel : PageModel
{
    private DBCtx Context { get; }
    public IndexModel(DBCtx _context)
    {
        this.Context = _context;
    }
 
    public void OnGet()
    {
    }
 
    [ValidateAntiForgeryToken]
    public JsonResult OnPostCheckEmail([FromBody] User user)
    {
        bool isValid = !this.Context.Users.ToList().Exists(p => p.Email.Equals(user.Email, StringComparison.CurrentCultureIgnoreCase));
        return new JsonResult(isValid);
    }
}
 
 
Razor Page (HTML)
The HTML of Razor Page 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 Anti-Forgery Token has been added to Razor Page using the AntiForgeryToken function of the HTML Helper class.
Note: For more details please refer my article, Sending AntiForgeryToken with AJAX requests in ASP.Net Core Razor Pages.
 
The HTML DIV consists of an HTML TextBox, an HTML Button and an HTML SPAN element.
There is a function named CheckAvailability inside the AngularJS Controller. The CheckAvailability function is called when the HTML Button is clicked.
Inside the CheckAvailability function, the $http service is used to make an AJAX call to the Handler method.
Note: If you want to learn more about these directives, please refer my article AngularJS: $http POST example with Parameters.
 
When the response is received, based on whether the Email Address is available or in use, appropriate message is displayed in the HTML SPAN element.
The ClearMessage function gets called when user types in the TextBox, it simply clears the message displayed in the HTML SPAN element.
@page
@model Check_Email_Angular_Razor_Core.Pages.IndexModel
@{
    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.3.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope, $http, $window) {
            $scope.CheckAvailability = function () {
                var antiForgeryToken = document.getElementsByName("__RequestVerificationToken")[0].value;
                var post = $http({
                    method: "POST",
                    url: "/Index?handler=CheckEmail",
                    dataType: 'json',
                    data: { Email: $scope.Email },
                    headers: {
                        "Content-Type": "application/json",
                        "XSRF-TOKEN": antiForgeryToken
                    }
                });
 
                post.success(function (data, status) {
                    if (data) {
                        //Email available.
                        $scope.Color = "green";
                        $scope.Message = "Email is available";
                    }
                    else {
                        //Email not available.
                        $scope.Color = "red";
                        $scope.Message = "Email is NOT available";
                    }
                });
 
                post.error(function (data, status) {
                    $window.alert(data.Message);
                });
            };
 
            $scope.ClearMessage = function () {
                $scope.Message = "";
            };
        });
    </script>
    @Html.AntiForgeryToken()
    <div ng-app="MyApp" ng-controller="MyController">
        Email:<input type="text" ng-model="Email" ng-keyup="ClearMessage()" />
        <input type="button" value="Show Availability" ng-click="CheckAvailability()" />
        <br/>
        <span ng-bind="Message" ng-style="{color:Color}"></span>
    </div>
</body>
</html>
 
 
Screenshot
ASP.Net Core Razor Pages: Check Email Availability (Exists) in Database using AngularJS
 
 
Downloads