我有一个自定义属性,该属性依赖于其他模型属性来起作用。该属性使用属性名称参数来从关联模型中获取值以执行验证。我将其附加到这样的字段中
AViewModel{
[DateBetweenAges(minProperty:"MinAge", maxProperty:"MaxAge", ErrorMessage = "Your age is not between {1} and {2}")]
public DateTime? DoB { get; set; }
public int MinAge { get; set; }
public int MaxAge { get; set; }
}
我已经通过使用适配器和AdaptorProvider进行了连接,以按照此处的示例Defining Custom Client Validation Rules in Asp.net Core MVC提供客户端验证但是我无法让错误消息说出正确的内容,例如:'Your age is not between 20 and 30'
20和30是附加到ViewModel的MinAge
和MaxAge
属性上的值(在加载页面时设置)
在适配器的GetErrorMessage(ModelValidationContextBasevalidationContext)方法中,我似乎根本无法获取ViewModel中的值。
在属性本身的IsValid
方法中,通过执行反射操作获得了这些值
var maxprop = validationContext.ObjectType.GetProperty(MaxProperty);
var maxPropVal = maxProperty.GetValue(validationContext.ObjectInstance, null);
但是这些似乎不是适配器中的对象实例,尽管检查确实使我进入了包含它的ViewData。
public class DateBetweenAgesAttributeAdapter : AttributeAdapterBase<DateBetweenAgesAttribute>
{
private readonly DateBetweenAgesAttribute _attribute;
public DateBetweenAgesAttributeAdapter(DateBetweenAgesAttribute attribute, IStringLocalizer localizer) : base(attribute, localizer)
{
_attribute = attribute;
}
public override void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
MergeAttribute(context.Attributes, "data-val-datebetweenages", GetErrorMessage(context));
MergeAttribute(context.Attributes, "data-val-datebetweenages-min", _attribute.MinProperty);
MergeAttribute(context.Attributes, "data-val-datebetweenages-max", _attribute.MaxProperty);
}
public override string GetErrorMessage(ModelValidationContextBase validationContext)
{
return GetErrorMessage(validationContext.ModelMetadata,
validationContext.ModelMetadata.GetDisplayName(),
//would like to pass the actual minvalue in here,
//would like to pass the actual maxvalue in here);
}
..
我该怎么办?
[我知道我可以为此使用[Remote]属性,但也许最终我会这样做,但这似乎意味着重复的工作。。
我通过将属性的属性放入Attribute类而不是Adapter的错误消息中来完成此工作,例如:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class DateBetweenAgesAttribute : ValidationAttribute {
public int MinProperty { get; set; }
public int MaxProperty { get; set; }
public DateBetweenAgesAttribute(int min, int max) : base() {
MinProperty = min;
MaxProperty = max;
ErrorMessage = $"Your age is not between {MinProperty} and {MaxProperty}";
}
}
然后您无需在DateBetweenAgesAttributeAdapter.GetErrorMessage中做任何事情,它照原样工作。