编辑记录时,自定义验证属性不起作用

时间:2016-05-01 18:06:04

标签: c# asp.net-mvc validationattribute

我有一个名为Doctor的实体,在创建医生表单中,我添加了自定义验证逻辑,如下所示:

$newtitle

然后在Doctor模型类中:

public class UniqueDoctorNameAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string name = value.ToString();
        HospitalEntities db = new HospitalEntities();
        int count = db.Doctors.Where(d => d.DoctorName == name).ToList().Count;
        if (count != 0)
            return new ValidationResult("A doctor already exists with that name");
        return ValidationResult.Success;
    }
}

并且在创建医生时它按预期工作,但它也显示在Doctor的编辑形式中,我知道解决这个问题的一种方法是在创建表单中使用viewmodel并在那里进行验证,但这需要很多因为我已经编写了很多代码,这取决于它是否传递了Doctor模型,所以我自己调试了,所以我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以更新自定义验证属性以接受您的Id属性,以便在对数据库进行检查时可以使用该属性。

public class UniqueDoctorNameAttribute : ValidationAttribute
{
    private readonly string _IdPropertyName;

    public UniqueDoctorNameAttribute(string IdPropertyName)
    {
        _IdPropertyName = IdPropertyName;
    }
    protected override ValidationResult IsValid(object value,
                                                      ValidationContext validationContext)
    {
        string name = value.ToString();
        var property = validationContext.ObjectType.GetProperty(_IdPropertyName);
        if (property != null)
        {
            var idValue = property.GetValue(validationContext.ObjectInstance, null);
            var db = new HospitalEntities();
            var exists = db.Doctors.Any(d => d.DoctorName == name && d.Id!=idValue);
            if (exists )
                   return new ValidationResult("A doctor already exists with that name");

            return ValidationResult.Success;
        }
        return ValidationResult.Success;
    }
}

当用户创建新记录时,DoctorId的值将为0,编辑时将为有效的doctorId值。

现在在您的视图模型中,

public class Doctor
{
    public int DoctorId { set; get; }

    [Required]
    [Display(Name = "Name")]
    [UniqueDoctorName(nameof(DoctorId))]
    public string DoctorName { get; set; }
}

nameof将返回字符串“DoctorId”(该属性的名称)。如果您的c#版本不支持此关键字,只需使用字符串“DoctorId”作为构造函数参数。