我试图从自定义验证属性的GetClientValidationRules方法中获取另一个属性的值.
这是我的尝试(基于另一个问题的Darin’s response):
public IEnumerable<ModelClientValidationRule> GetClientValidationRules( ModelMetadata Metadata,ControllerContext context) { var parentType = Metadata.ContainerType; var parentMetaData = ModelMetadataProviders.Current .GetMetadataForType(null,parentType); var parentMetaData = ModelMetadataProviders.Current .GetMetadataForProperties(context.Controller.ViewData.Model,parentType); var otherProperty = parentMetaData.FirstOrDefault(p => p.PropertyName == "SomeProperty"); var otherValue = otherProperty.Model; var rule = new ModelClientValidationRule { ValidationType = "customvalidatorattribute",ErrorMessage = this.FormatErrorMessage(Metadata.GetDisplayName()),}; yield return rule; }
但是,在尝试设置otherValue时,我得到:
System.Reflection.TargetException: Object does not match target type.