Validating an object exists when editing
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(stri开发者_运维技巧ng 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?
Pass in a extra flag to indicate what mode you're in, e.g. bool isEditMode
and based on that, tweak your results. You can use AdditionalFields attribute to pass in that info; Also, take a look here: Remote Validation in ASP.Net MVC 3: How to use AdditionalFields in Action Method
You can solve this problem by using two different viewmodels in which you derive the one from the other: the superclass can be used for editing, the subclass is for inserts with remote validation.
public class EmployeeViewModel // The normal one, can be used for editing
{
[ScaffoldColumn(false)]
public int EmployeeId { get; set; }
public virtual string Username { get; set; }
}
public class InsertEmloyeeViewModel : EmployeeViewModel
{
[Remote("UsernameExists", "Employees", ErrorMessage = "Username already exists")]
public override string Username { get; set; }
}
When the edit-functionlity also contains some 'specialities', you could derive a third class 'EditEmployeeViewModel' from the base class EmployeeViewmodel.
精彩评论