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 jQuery AJAX and Entity Framework in ASP.Net Core Razor Pages.
This article will illustrate how to check Username availability in database on Registration Form by making AJAX call to database using jQuery AJAX 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 Username Availability (Exists) in Database using jQuery AJAX
 
I have already inserted few records in the table.
ASP.Net Core Razor Pages: Check Username Availability (Exists) in Database using jQuery AJAX
 
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 Username Availability (Exists) in Database using jQuery AJAX
 
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_UserName_jQuery_Razor_Core.Models;
using Microsoft.EntityFrameworkCore;
 
namespace Check_UserName_jQuery_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 jQuery AJAX operation
This Handler method handles the call made by the jQuery AJAX function 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 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 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 OnPostCheckUsername(string username)
    {
        bool isValid = !this.Context.Users.ToList().Exists(p => p.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase));
        return new JsonResult(isValid);
    }
}
 
 
Razor Page (HTML)
The HTML of Razor Page consists of an HTML TextBox, an HTML Button and an HTML SPAN element.
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 TextBox has been assigned an OnKeyUp event handler which triggers the ClearMessage JavaScript function.
The HTML Button has been assigned an OnClick event handler which triggers the CheckAvailability JavaScript function.
Inside CheckAvailability JavaScript function, the value of the Anti-Forgery Token is read from the Hidden Field and passed as Request Header in the jQuery AJAX call and value of the TextBox is passed as parameter.
The URL for the jQuery AJAX call is set to the handler method of the Razor PageModel i.e. /Index?handler=CheckUsername and then the Handler method is called using jQuery AJAXfunction.
Note: In the Razor PageModel, the Handler method name is OnPostCheckUsername but here it will be specified as CheckUsername when calling from the Razor HTML Page.
 
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.
@page
@model Check_UserName_jQuery_Razor_Core.Pages.IndexModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @Html.AntiForgeryToken()
    Username:
    <input id="txtUsername" type="text" onkeyup="ClearMessage()" />
    <input id="btnCheck" type="button" value="Show Availability" onclick="CheckAvailability()" />
    <br/>
    <span id="message"></span>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        function CheckAvailability() {
            var username = $("#txtUsername").val();
            var token = $('input:hidden[name="__RequestVerificationToken"]').val();
            $.ajax({
                type: "POST",
                url: "/Index?handler=CheckUsername",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN", token);
                },
                data: { username: username },
                success: function (response) {
                    var message = $("#message");
                    if (response) {
                        //Username available.
                        message.css("color", "green");
                        message.html("Username is available");
                    }
                    else {
                        //Username not available.
                        message.css("color", "red");
                        message.html("Username is NOT available");
                    }
                }
            });
        };
 
        function ClearMessage() {
            $("#message").html("");
        };
    </script>
</body>
</html>
 
 
Screenshot
ASP.Net Core Razor Pages: Check Username Availability (Exists) in Database using jQuery AJAX
 
 
Downloads