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: , , ,

23 Responses

Subscribe to comments with RSS.

  1. links for 2009-12-21 « 2LeggedSpider said, on December 21, 2009 at 12:33 pm

    […] Check availability of Username using ASP.NET MVC and jQuery (tags: jquery, asp.net, mvc, aspnetmvc) […]

  2. rana said, on January 4, 2010 at 11:51 am

    nice tutorial , thanks for sharing…

  3. Neeta said, on January 7, 2010 at 10:07 am

    hi,

    I am using master pages and my text box is inside a content place holder.

    How do I access this text box id from the script. Can someone please mail

    • 2leggedspider said, on January 7, 2010 at 5:50 pm

      Hi Neeta,

      If you are using ASP.NET MVC then $(“#TEXTBOXID”) will get you the handler to the text box.

      In case of ASP.NET Webforms the ClientID is generated at runtime. For instance the ID of the text box would be something like ctl01_Content1_txtUserName. To access this text box in jQuery you would have to do something like this…

      $(“[id$=’_txtUserName’]”);

      $(“[id$=’_txtUserName’]”).attr(“id”) will get you the complete ID.

      Hope it is clear!

      Cheers,
      Sumit

  4. Neeta said, on January 9, 2010 at 8:56 am

    Hi Sumit,

    Thanks for your reply. Can you please tell what is ‘Home’ in following line. Is it a directory or some mvc convention. I have my test.aspx file which has the text box and script etc in main directory and the UniqueNameController.cs file in App_code folder in visual studio.
    $.post(“/Home/CheckName”, { username: name },

    Thanks
    Neeta

  5. Neeta said, on January 10, 2010 at 3:10 am

    Hi Sumit,

    Is it possible for you to mail me a zip file for this project.

    Thanks

    Neeta

  6. ASP.NET MVC Archived Buzz, Page 1 said, on February 27, 2010 at 2:54 am

    […] to Vote[Del.icio.us] Check availability of Username using ASP.NET MVC and jQuery « 2LeggedSpider (2/26/201…Friday, February 26, 2010 from […]

  7. zynga said, on March 20, 2010 at 8:45 am

    i am usually jumping on the online world the majority of the night which means that I have the inclination to read significantly, which unfortunately isn’t typically a beneficial factor as the largest part of the web sites I discover are constructed of pointless crap copied from some other internet websites a thousand times, on the other hand I gotta say this blog is definitely enjoyable and holds some authentic information, so thank you for stopping the phenomena of solely duplicating other people’s blogs and forums, if you ever wanna have fun with playing a few hands of facebook poker together with me let me know – you have my email address 🙂

  8. praveen said, on August 28, 2010 at 2:58 pm

    Hi…Sumit..

    Nice to see all your sharings. And am recently completed my DotNet course and intrested to share things like you .So please help me out by giving good materials to me..Right now am working as Trainee in AJTech ..

    you can send me at praveen.share@yahoo.co.in.

  9. Kendall Vanderkam said, on December 31, 2010 at 5:33 am

    Hey I just wanted to let you know, I really like the written material on your web site. But I am employing Firefox on a machine running version 9.10 of Ubuntu and the look and feel is not quite right. Not a strong deal, I can still essentially read the posts and explore for information, but just wanted to inform you about that. The navigation bar is kind of hard to use with the config I’m on. Keep up the great work!

  10. Purushothaman said, on January 5, 2013 at 7:02 am

    Hi Sumit,

    i tried the code in my MVC application for email validation, at it didnt worked, but after removing the threading in the controller it works fine……
    please if possible can you tell me the reason for that….

    Thank you…

  11. sagar said, on January 21, 2014 at 8:04 am

    Hi…

    I have implement the code given by you….but it cant work….

    $(document).ready(function () {

    $(“#Username”).blur(function () {
    var name = $(“#Username”).val(); //Value entered in the text box
    var status = $(“#userMsg”); //DIV object to display the status message

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

    });

    public ActionResult CheckUserName(FormCollection form)
    {
    //int isExists = 0;
    //if (!string.IsNullOrEmpty(username))
    //{
    // var result = (from a in db.Users where a.Username == username select a).Count();
    // if (result == 0)
    // {
    // isExists = 0;
    // }
    // else
    // {
    // isExists = 1;
    // }

    //}
    //else
    //{
    // isExists = -1;
    //}
    //return Json(isExists);
    string name = form[“username”];
    var result = (from a in db.Users where a.Username == name select a).Count();
    if (result == 0)
    {
    return Json(true);
    }
    else
    {
    return Json(false);
    }

    }

    When it returns the true or false……it doesn’t goes into function
    (data)in javascript

    can you help me

  12. 国内即発 3日間限定 said, on November 27, 2015 at 4:02 am

    このサイトなどの兄推奨 I 。彼た 右。この公開 実際私の一日行わ。あなたは望めない どのそんなに私はこのために費やしていた時間| ただただ 検討信じ! !
    国内即発 3日間限定 http://cosmicgroupin.com

  13. 最短翌日お届け 一部予約販売 said, on November 27, 2015 at 4:03 am

    美少女 見て前方 再び訪問|戻す|再び戻ってきます。
    最短翌日お届け 一部予約販売 http://phatgiaokiengiang.com

  14. 国内即発 3日間限定 said, on November 27, 2015 at 4:04 am

    こんにちは、私が考える私はその| ウェブサイト そう ソー気づいはあなたが私を訪れた私は来ましたに戻る たい 私は?しよう 問題私のウェブサイト!| 高める改善の を利用するために使用すること あなたアイデア !!
    国内即発 3日間限定 http://cosmicgroupin.com

  15. 海外限定 国内即発 said, on November 27, 2015 at 4:05 am

    紛れもなく | あなたはこれを使用することをそれは想像。あなたのお気に入りの 理由 のようだった 上に ウェブ 最も簡単 | に取ります。 しながら、一方と同時に 心配 について知る|認識|理解|認識|ない} {実現ん|悩み|彼らは明らかにすることを課題。あなたは、| トップ時に釘を打つこと制御管理する も 定義さアウト全部 ことなく 副作用、必要とせずに人 でき信号を取ることができます。 おそらくになります|多くを得るために、再度です。
    海外限定 国内即発 http://stormmasterexteriors.com

  16. この優れたウェブサイト 間違いなく すべてのすべてを持つI必要な これについて主題に関すると依頼するのかわかりませんでした。
    当店の商品全て正規品 国内即発 http://itvestak.org.rs

  17. 正規販売店 完売これで最後 said, on November 27, 2015 at 4:06 am

    このウェブサイト 本当に 私が欲しかった これについて主題に関すると依頼するのかわかりませんでした。
    正規販売店 完売これで最後 http://adeykin.ru

  18. 安い一番よい 国内即発 said, on November 27, 2015 at 4:08 am

    のためにあなたに感謝し、 素晴らしい読み! I 確かそれ| |すべてののビットの少しを 楽しん愛さ。あなたは私がしている ブックマーク チェックアウトする 新しいものあなたポスト…
    安い一番よい 国内即発 http://alexandersnoek.com

  19. 日本一安い激安 国内即発 said, on November 27, 2015 at 4:08 am

    ちょっとそこ サイトブログブラウザの互換性の問題を持つ可能性があります、私はあなたが考えます。で 私はあなたを見てみるとサファリ、それが正常に見えるが、Internet Explorerで開くときに、それはいくつかの重複があります。私はちょうどあなたに素早く頭を放棄したかったです!ブログという、素晴らしい [その他!
    日本一安い激安 国内即発 http://www.coonectio.com

  20. Dian said, on May 8, 2016 at 8:02 am

    Hi,
    can you send me this project to dfordiyan@gmail.com?
    Thank you :))


Leave a comment