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 MVC.
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 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 jQuery AJAX
 
I have already inserted few records in the table.
ASP.Net Core MVC: 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 JSON Serializer setting
First you need to configure the 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_jQuery_MVC_Core.Models;
using Microsoft.EntityFrameworkCore;
 
namespace Check_UserName_jQuery_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 AJAX 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 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(string username)
    {
        bool isValid = !this.Context.Users.ToList().Exists(p => p.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase));
        return Json(isValid);
    }
}
 
 
View
The View consists of an HTML TextBox, an HTML Button and an HTML SPAN element.
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, ASP.Net Core MVC: Using AntiForgery Token with jQuery AJAX.
 
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 AntiForgery Token and value of the TextBox is passed as parameter.
The URL for the jQuery AJAX call is set to the Controller’s Action method i.e. /Home/AjaxMethod and then the Controller’s Action method is called using jQuery AJAX function.
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>
    @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[name="__RequestVerificationToken"]').val();
            $.ajax({
                type: "POST",
                url: "Home/AjaxMethod",
                data: {
                    __RequestVerificationToken: token,
                    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 MVC: Check Username Availability (Exists) in Database using jQuery AJAX
 
 
Downloads