我需要使用资源来获取数据注释属性的错误消息 即时通过在global.asax
中注册DataAnnotationAdapter来实现此目的这是我的适配器
public class ExternalResourceDataAnnotationsValidator : DataAnnotationsModelValidator<ValidationAttribute>
{
/// <summary>
/// The type of the resource which holds the error messqages
/// </summary>
public static Type ResourceType { get; set; }
/// <summary>
/// Function to get the ErrorMessageResourceName from the Attribute
/// </summary>
public static Func<ValidationAttribute, string> ResourceNameFunc
{
get { return _resourceNameFunc; }
set { _resourceNameFunc = value; }
}
private static Func<ValidationAttribute, string> _resourceNameFunc = attr => attr.GetType().Name;
public ExternalResourceDataAnnotationsValidator(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute)
: base(metadata, context, attribute)
{
if (Attribute.ErrorMessageResourceType == null)
{
this.Attribute.ErrorMessageResourceType = ResourceType;
}
if (Attribute.ErrorMessageResourceName == null)
{
this.Attribute.ErrorMessageResourceName = ResourceNameFunc(this.Attribute);
}
}
}
以下是我在global.asax
中注册的方式ExternalResourceDataAnnotationsValidator.ResourceType = typeof(Resources);
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(ExternalResourceDataAnnotationsValidator));
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RangeAttribute), typeof(ExternalResourceDataAnnotationsValidator));
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MaxLengthAttribute), typeof(ExternalResourceDataAnnotationsValidator));
此代码不提供客户端验证,因为它不会返回任何客户端验证规则
我的问题是如何知道将ValidationType放入下面的方法
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var rm = new ResourceManager(ResourceType);
var msg =rm.GetString(ResourceNameFunc(this.Attribute));
return new[] {new ModelClientValidationRule() {ErrorMessage = msg, ValidationType ="??????"},};
}