Doctor というエンティティがあり、Create 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 モデル クラスで次のようにします。
public class Doctor
{
[Required]
[Display(Name = "Name")]
[UniqueDoctorName]
public string DoctorName { get; set; }
}
Doctor を作成するときに期待どおりに動作しますが、Doctor の編集フォームにも表示されます。これを修正する 1 つの方法は、作成フォームでビューモデルを使用してそこで検証を行うことですが、それには多くのデバッグが必要になります。ドクターモデルに渡されることに応じて多くのコードを書いたので、どうすればそれを修正できますか?