2LeggedSpider

Check availability of Username using ASP.NET MVC and jQuery

Posted in AJAX, ASPNETMVC, jquery by Sumit Thomas on August 17, 2009

[tweetmeme style=”compact”]Here is a simple way to check if an Username is available using ASP.NET MVC and jQuery

Step 1: First lets create the XHTML markup for our View page(Index) as follows…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Check if an Username already exists</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
//Your jQuery code will come here
</script>
</head>
 
<body>
    Enter a Username: <br />
    <input type="text" id="txtUsername" />
    <input type="button" id="btnCheck" value="Check!" />
    <div id="divStatus" />
</body>
</html>

So your view will look like this…

jQuery Username check

Step 2: Create a Controller class ‘UniqueNameController’ or WhateverController as follows…

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyMVCTrials.Controllers
{
    [HandleError]
    public class UniqueNameController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult CheckName(FormCollection form)
        {
            System.Threading.Thread.Sleep(3000);
            string name = form["username"];

            if (name.Equals("Sumit")) 
                return Json(false);
            return Json(true);
        }
    }
}

The Action Method CheckName contains the logic to check if the Username provided already exists or not. The code provided here is only for demo. Thread.Sleep(3000) will simulate a delay as if to show that the application is working really hard to find out if the username exists or not. REMOVE that line when you are writing the actual code to check the username against a database or Web service.

NOTE: The return value need not be a JsonResult. You can change it to ActionResult and return some string value to indicate the success/failure of the call.

Step 3: Lets replace the comment Your jQuery code will come here from our view with the following jQuery code…

        $(document).ready(function() {
            $("#btnCheck").click(function() {
                var name = $("#txtUsername").val(); //Value entered in the text box
                var status = $("#divStatus"); //DIV object to display the status message
                status.html("Checking....") //While our Thread works, we will show some message to indicate the progress

                //jQuery AJAX Post request
                $.post("/Home/CheckName", { username: name },
                    function(data) {
                        if (data == "true") {
                            status.html(name + " is available!");
                        } else {
                            status.html(name + " is not available!");
                        }
                    });
            });
        });

The code is very simple. The button click event makes an AJAX call to our ActionMethod CheckName and expects a response. The Thread.Sleep(3000) will delay the response for 3 seconds. The ActionMethod checks the value of the username and returns a JSON string for our AJAX call to handle.

We can fancy it up a bit by providing some color to our status messages using the jQuery addClass method. Putting it all together, our View will looks as follows…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Check If Name Already Exists</title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <style type="text/css">
        .green
        {
            color: Green;
        }
        .red
        {
            color: Red;
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnCheck").click(function() {
                var name = $("#txtUsername").val();
                var status = $("#divStatus");
                status.html("Checking....").removeClass();
                $.post("/Home/CheckName", { username: name },
                    function(data) {
                        if (data == "true") {
                            status.html(name + " is available!").addClass("green");
                        } else {
                            status.html(name + " is not available!").addClass("red");
                        }
                    });
            });
        });
    </script>
</head>
<body>
    Enter a Username:
    <br />
    <input type="text" id="txtUsername" />
    <input type="button" id="btnCheck" value="Check!" />
    <div id="divStatus" />
</body>
</html>

Checking the username
Progress

Username already exists
Not Available

Username is available
Available

There are different ways in which you can make AJAX requests using jQuery. For the detailed documentation check http://docs.jquery.com/Ajax. Hope it was useful!

Tagged with: , , ,