[英]Custom validation attribute's ValidationContext is missing a field
[英]Custom Validation Attribute reading from a form field
我正在嘗試創建自己的驗證屬性IsUnique
,該屬性檢查給定屬性的現有值。 我了解必須重寫IsValid()
才能使自定義驗證屬性起作用。 到目前為止,我已經看到帶有帶有字符串參數的validate屬性的示例,然后將這些參數與IsValid()
方法中的硬編碼值進行比較。
我需要IsValid()
方法來訪問屬性及其值,以進一步將其與數據庫中的值進行比較。
到目前為止,這是我所做的:
public class IsUnique : ValidationAttribute
{
private string codeno { get; set; }
: base("{0} is already in use")
public IsUnique (string codeno)
{
this.codeno = codeno;
}
public override ValidationResult IsValid(object value,
ValidationContext vContext)
{
if (value != null)
{
MyDBContext db = new MyDBContext();
Student studentsCodeNo =
db.Students.FirstOrDefault(r => r.codeno== (string)value);
if (studentsCodeNo != null)
{
string errorMessage =
FormatErrorMessage(vContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
}
如前所述,問題在於該版本帶有參數。 我希望從用戶表單字段中讀取codeno
,然后將此類值與數據庫中的任何內容進行比較。 我不知道如何從表單字段讀取值。
這是代碼
public class IsUnique : ValidationAttribute{
public override ValidationResult IsValid(object value,
ValidationContext vContext)
{
PropertyInfo property = validationContext.ObjectType.GetProperty("Codeno");
if (property == null)
return new ValidationResult(string.Format("Property '{0}' is undefined","Codeno"));
var fieldValue = property.GetValue(validationContext.ObjectInstance, null);
string codeno= (fieldValue == null ? "" : fieldValue.ToString());
if (!string.IsNullOrEmpty(codeno))
{
MyDBContext db = new MyDBContext();
Student studentsCodeNo =
db.Students.FirstOrDefault(r => r.codeno== codeno);
if (studentsCodeNo != null)
{
string errorMessage =
FormatErrorMessage(vContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success; }}
已經有一些現成的方法可以做到這一點http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.schema.indexattribute(v=vs.113).aspx
[Index(IsUnique=true)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.