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 MVC Razor.
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 MVC Razor.
 
 
Database
I have made use of the following table Users with the schema as follows.
Check Username Availability (Exists) in Database using jQuery AJAX in ASP.Net MVC
 
I have already inserted few records in the table.
Check Username Availability (Exists) in Database using jQuery AJAX in ASP.Net MVC
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Note: For beginners in ASP.Net MVC and Entity Framework, please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework.
 
Check Username Availability (Exists) in Database using jQuery AJAX in ASP.Net MVC
 
 
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 jQuery AJAX function in the View.
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 return type of the Action method is JsonResult, for more details please refer ASP.Net MVC JsonResult example.
 
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public JsonResult CheckUsername(string username)
    {
        UsersEntities entities = new UsersEntities();
        bool isValid = !entities.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 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.
The CheckAvailability JavaScript function first fetches the Username to be checked for availability from the TextBox and then calls the Controller’s Action method using the 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 JavaScript 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>
    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();
            $.ajax({
                type: "POST",
                url: "/Home/CheckUsername",
                data: '{username: "' + username + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                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
Check Username Availability (Exists) in Database using jQuery AJAX in ASP.Net MVC
 
 
Downloads