This is extremely silly, but I can't for the life of me figure it out.
I want to validate that an Employee username doesn't already exist when adding or editing an Employee. Here's my view model:
public class EmployeeViewModel
{
[ScaffoldColumn(false)]
public int EmployeeId { get; set; }
[Remote("UsernameExists", "Employees", ErrorMessage = "Username already exists")]
public string Username { get; set; }
}
And in my controller:
public ActionResult UsernameExists(string username)
{
return Json(!_employeesRepository.UsernameExists(username), JsonRequestBehavior.AllowGet);
}
The function in the employee repository:
public bool UsernameExists(string username)
{
return Employees.Where(e => e.Username.ToLower().Equals(username.ToLower())).Count() > 0;
}
This works great when I'm creating an Employee. But if I'm editing one and I try to save it, I get an error that the username already exists (which is true). So I need to somehow tell the function that it's okay the username exists if I'm editing an Employee with that username.
Is this possible with remote validation?