Wednesday, 3 January 2018

Check Username Availability (Exists) in Database using jQuery AJAX in ASP.Net MVC

Check Username Availability (Exists) in Database using jQuery AJAX in ASP.Net MVC

Description:

In this example we explain that how to check username availability in database using jQuery Ajax in MVC.or how to check user name exists in current database or not using jQuery Ajax Call in MVC Razor. Or check whether username is available in database or not in MVC using jQuery Ajax. Or client side check the username is existing or not using jQuery Ajax in MVC.
Controller:

public class EmployeeController : Controller
    {

        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:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Check Username Availability (Exists) in Database using jQuery AJAX in ASP.Net MVC</title>
</head>
<body>
    Email:
    <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: "/Employee/CheckUsername",
                data: '{username: "' + username + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var message = $("#message");
                    if (response) {
                        //Email available.
                        message.css("color", "green");
                        message.html("Email is available");
                    }
                    else {
                        //Email not available.
                        message.css("color", "red");
                        message.html("Email is NOT available");
                    }
                }
            });
        };

        function ClearMessage() {
            $("#message").html("");
        };
    </script>
</body>
</html>


0 comments:

Post a Comment