Try like this:
Define model property in your Model class:
public class Login{
[Required]
[Remote("IsUserNameAvaliable", "Home")]
public string username{get;set;}
[Required]
public string password{get;set;}
}
The Remote attribute that is placed will find the Method/Action with IsUserNameAvaliable in the controller name Home.
The remote attribute servers for this purpose in MVC.
public JsonResult IsUserNameAvaliable(string username)
{
//Check if there are any matching records for the username name provided
if (_dbEntity.Users.Any(c => c.UserName == username))
{
//If there are any matching records found
return Json(true, JsonRequestBehavior.AllowGet);
}
else
{
string userID = String.Format(CultureInfo.InvariantCulture,
"{0} is not available.", username);
return Json(userID, JsonRequestBehavior.AllowGet);
}
}
Now in your view strongly type the textbox
@model Application.Models.Login
@Html.TextBoxFor(m=>m.username)
@Html.ValidationMessageFor(m=>m.username)
Donot forget to include jquery validation scripts.
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")