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?
[Remote]attribute? You error is most likely becauseprevUseris null (no match was found) soprevUser.usernamethrows an exception. You can confirm this by inspecting the response (Network tab of your browser tools)if (prevUser.username == username)really makes so sense since your getting the object withp => p.username == username- instead you should just checkif (prevUser == null) { return Json(false); } else { return Json(true); }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).