MVC模型自定义控件属性

时间:2014-09-09 14:50:18

标签: asp.net-mvc-4

我正在使用自定义uniqueemail确认属性,如

public class UniqueEmailAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        WMContext db = new WMContext();
        var userWithTheSameEmail = db.Users.SingleOrDefault(
            u => u.email == (string)value);
        return userWithTheSameEmail == null;
    }

}

插入用户时工作正常。但是,当我尝试更新用户时,它会出错。

public class User
{
    public int userID { get; set; }

    [Required]
    [Display(Name = "Name")]
    public string name { get; set; }

    [Required]
    [Display(Name = "Email")]
    [UniqueEmail(ErrorMessage = "This email is used by another user")]
    public string email { get; set; }
}

解决方案:我已经改变了这样的IsValid方法:

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var model = (User)validationContext.ObjectInstance;
        WMContext db = new WMContext();
        var userWithTheSameEmail = db.Users.SingleOrDefault(
            u => u.email == (string)value && u.userID!=model.userID);
        if (userWithTheSameEmail!=null)
        {
            return new ValidationResult("Bu eposta adresi kullanılıyor.");
        }
        return ValidationResult.Success;
    }

0 个答案:

没有答案