Özelliğimin değerini, model sınıfımdaki başka bir özelliğin değeriyle karşılaştırmak istediğim özel bir doğrulama özniteliği oluşturmak istiyorum. Benim modeli sınıfında var Örneğin :Özel doğrulama özelliği nasıl oluşturulur?
...
public string SourceCity { get; set; }
public string DestinationCity { get; set; }
Ve özel bir oluşturmak istiyorum bu gibi kullanmak için özellik:
[Custom("SourceCity", ErrorMessage = "the source and destination should not be equal")]
public string DestinationCity { get; set; }
//this wil lcompare SourceCity with DestinationCity
Oraya nasıl olabilir?
public class CustomAttribute : ValidationAttribute
{
private readonly string _other;
public CustomAttribute(string other)
{
_other = other;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(_other);
if (property == null)
{
return new ValidationResult(
string.Format("Unknown property: {0}", _other)
);
}
var otherValue = property.GetValue(validationContext.ObjectInstance, null);
// at this stage you have "value" and "otherValue" pointing
// to the value of the property on which this attribute
// is applied and the value of the other property respectively
// => you could do some checks
if (!object.Equals(value, otherValue))
{
// here we are verifying whether the 2 values are equal
// but you could do any custom validation you like
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
}
http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx – Joe
@Joe, bu ASP.NET MVC 2 içindir ve artık MVC 3 için geçerli değildir. Gönderi, OP'nin burada elde etmeye çalıştığı şey olan doğrulayıcı özellikteki değerleme değerinin nasıl alınacağını göstermez. –