0

I'm using asp.net MVC 4 and jQuery 1.9.1 to check username availability when user inputs the username in textfield. For some reason I'm getting Internal Server Error 500 in my browser console.

Here is my code:

Controller

    [HttpPost]
    public JsonResult chkPrevUser(string username)
    {
        var prevUser = rentdb.Regs.Where(p => p.username == username).FirstOrDefault();

        if (prevUser.username == username)
        {
            return Json(false);
        }
        else
        {
            return Json(true);
        }
    }

View

<script>
    $(function () {
        $("#txtUsername").keyup(function () {
            var name = $("#txtUsername").val();
            var status = $("#userStatus");
            var user = $.trim(name);
            if (user.length > 3) {
                status.html("Checking....")
                $.post("/Home/chkPrevUser", { username: name },
                            function (data) {
                                if (data == true) {
                                    status.html("<font color=green>'<b>" + name + "</b>' is available!</font>");
                                } else {
                                    status.html("<font color=red>'<b>" + name + "</b>' is not available!</font>");
                                }
                            });
            } else {
                status.html("Need more characters...");
            }
        });
    });
</script>
@using (Html.BeginForm("Register", "Home"))
{
    @Html.TextBoxFor(a => a.username, new { id = "txtUsername" })
    @Html.ValidationMessageFor(a => a.username)
}

Is there something wrong in my code? How can I solve this issue and check if username exists already by ajax?

6
  • Is there any reason your not using a [Remote] attribute? You error is most likely because prevUser is null (no match was found) so prevUser.username throws an exception. You can confirm this by inspecting the response (Network tab of your browser tools) Commented Dec 20, 2015 at 8:32
  • 1
    And if (prevUser.username == username) really makes so sense since your getting the object with p => p.username == username - instead you should just check if (prevUser == null) { return Json(false); } else { return Json(true); } Commented Dec 20, 2015 at 8:34
  • It also makes no sense to be calling this on keyup() - your making an unnecessary call to the server which will always return false (once the code is corrected) until the user has actually finished typing the user name (and as a result displaying a meaningless error message). Commented Dec 20, 2015 at 8:40
  • Thanks for your awesome tips @StephenMuecke, I admit that was stupid of me! You could post your tips as an answer if you want. Commented Dec 20, 2015 at 8:58
  • 1
    Will add an answer with more detail shortly :) Commented Dec 20, 2015 at 9:05

3 Answers 3

1

The 500 (Internal Server Error) is thrown because your query

var prevUser = rentdb.Regs.Where(p => p.username == username).FirstOrDefault();

will return null of no match is found, so your following line of code

if (prevUser.username == username)

will throw a NullReferenceException because you cannot access the username property of null

Change the code to

if (prevUser == null)
{
    return Json(false);
}
else
{
    return Json(true);
}

However I recommend that you delete your script and instead use a RemoteAttribute, which would applied to you property as

[Remote("chkPrevUser", ErrorMessage = "The user name already exists")]
public string username { get; set; }

The controller method just needs to be changed to [HttpGet] and the return statements changed to add the JsonRequestBehavior.AllowGet parameter (e.g. return Json(true, JsonRequestBehavior.AllowGet);). For more information, refer How to: Implement Remote Validation in ASP.NET MVC

If however you choose to keep your script, I suggest the following changes

  1. Handle the .change() event rather than .keyup(). Currently if the user was trying to enter a 10 character user name, an unnecessary call is made to server on the 4th through to 9th characters which would return an annoying and meaningless error message. Note the RemoteAttribute initially handles the .change() event (i.e. validation is not performed until the user tabs out of the textbox), and if its invalid, then handles the .keyup() event if the user makes an edit.

  2. Use '@Url.Action("chkPrevUser", "Home")' instead of "/Home/chkPrevUser" to ensure your url's are always correctly generated

Sign up to request clarification or add additional context in comments.

Comments

0

Server Error 500 means the server throws an exception in most of the times. Debug your method and see what cause the exception.

Comments

0

[Remote] attribute should work like a charm on this. Try these steps , it worked for my Application.

1) Viewmodel Class in Model folder

[Remote("IsAlreadySigned", "User", HttpMethod = "POST", ErrorMessage = "Username already exists in database. Try another Username")]
        public string Username { get; set; }

2) Create these 2 Action in User Controller.

[HttpPost]
        public JsonResult IsAlreadySigned(string Username)
        {

            return Json(IsUserAvailable(Username));

        }
        public bool IsUserAvailable(string UserN)
        {
            // Assume these details coming from database  
            List<UserVM> RegisterUsers = new List<UserVM>()
        {

            new UserVM {Username = UserN }

        };
            using (Db db = new Db())
            {


                var UserId = db.User.Where(x => x.Username == UserN).Select(x => new { UserN }).FirstOrDefault();

                bool status;
                if (UserId != null)
                {
                    //Already registered  
                    status = false;
                }
                else
                {
                    //Available to use  
                    status = true;
                }


                return status;
            }
        }

3) Create new View "Signup" with UserVM class Model.

Now, try and you will see error as soon as you tab out from Username field in Signup form.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.