In this article I will explain with an example, how to check Username availability i.e. check whether Username exists in database or not using AngularJS and Entity Framework in ASP.Net Core MVC.
This article will illustrate how to check Username availability in database on Registration Form by making AJAX call to database using AngularJS and Entity Framework in ASP.Net Core MVC.
 
 
Database
I have made use of the following table Users with the schema as follows.
ASP.Net Core MVC: Check Username Availability (Exists) in Database using AngularJS
 
I have already inserted few records in the table.
ASP.Net Core MVC: Check Username 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
First you need to configure the Anti-Forgery Token and JSON Serializer settings in the Startup.cs file.
 
 
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 and Entity Framework, please refer my ASP.Net Core: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework with ASP.Net Core.
 
using Check_UserName_Angular_MVC_Core.Models;
using Microsoft.EntityFrameworkCore;
 
namespace Check_UserName_Angular_MVC_Core
{
    public class DBCtx : DbContext
    {
        public DBCtx(DbContextOptions<DBCtx> options) : base(options)
        {
        }
 
        public DbSet<User> Users { get; set; }
    }
}
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling AJAX POST operation
This Action method handles the call made by the AngularJS function in the View.
Attributes
HttpPost: The HttpPost attribute which signifies that the method will accept Http Post requests.
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 UserName property holds the value of the TextBox sent from the AngularJS $http service.
The value of the Username is compared with the records from the Users table fetched using Entity Framework with the help of Lambda expression.
If the Username does not exists in the Users table, then True value is returned and if it exists then False value is returned.
Note: The following Action method handles POST call and will return JSON object and hence the return type is set to JsonResult. For more details please refer ASP.Net Core: Return JSON from Controller in ASP.Net Core MVC.
 
public class HomeController : Controller
{
    private DBCtx Context { get; }
    public HomeController(DBCtx _context)
    {
        this.Context = _context;
    }
 
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult AjaxMethod([FromBody] User user)
    {
        bool isValid = !this.Context.Users.ToList().Exists(p => p.UserName.Equals(user.UserName, StringComparison.CurrentCultureIgnoreCase));
        return Json(isValid);
    }
}
 
 
View
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 Anti-Forgery Token has been added to View using the AntiForgeryToken function of the HTML Helper class.
Note: For more details please refer my article, Using AntiForgery Token with jQuery AJAX in ASP.Net MVC.
 
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 Controller’s Action 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 Username 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.
@{
    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: "/Home/AjaxMethod",
                    dataType: 'json',
                    data: { UserName: $scope.Username },
                    headers: {
                        "Content-Type": "application/json",
                        "XSRF-TOKEN": antiForgeryToken
                    }
                });
 
                post.success(function (data, status) {
                    if (data) {
                        //Username available.
                        $scope.Color = "green";
                        $scope.Message = "Username is available";
                    }
                    else {
                        //Username not available.
                        $scope.Color = "red";
                        $scope.Message = "Username 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">
        Username:<input type="text" ng-model="Username" 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 MVC: Check Username Availability (Exists) in Database using AngularJS
 
 
Downloads