我使用了一个自定义验证属性-AmountShouldBeLessOrEqualAttribute
-,该属性的验证过程与另一个属性的值有关,并且此属性成功。
但是在以下情况下,我遇到了问题:
ModelBinding
过程导致ErrorMessage
属性中AmountShouldBeLessOrEqual
的值被格式化。例如:
在
ViewModel
中,有一个Amount
属性具有上述特征和
其错误消息:
Your amount should be less than {0}
将被转换为:
Your amount should be less than 23
注意:
23
是MaxAmount
中ViewModel
属性的值
现在我将MaxAmount
更改为83
ModelBinding
过程将开始AmountShouldBeLessOrEqualAttibute
的验证过程。现在,如果我看到ErrorMessage属性的值它不是 Your amount should be less than {0}
,它将保留为旧格式的文本:Your amount should be less than 23
。因此无法将其再次格式化为Your amount should be less than 83
我的问题:
每次使用新值进行格式化时,如何将格式化的ErrorMessages
重置为其Non-Formatted
版本?
在ViewModel
中:
[AmountShouldBeLessOrEqual(nameof(MaxAmount), ErrorMessage = "Your amount should be less than {0}")]
public decimal Amount { get; set; }
public decimal MaxAmount { get; set; }
AmountShouldBeLessOrEqualAttribute
:
public class AmountShouldBeLessOrEqualAttribute : ValidationAttribute
{
private readonly string _comparisonProperty;
public AmountShouldBeLessOrEqualAttribute(string comparisonProperty)
{
_comparisonProperty = comparisonProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ErrorMessage = ErrorMessageString;
var currentValue = (decimal)value;
var comparisonValue = GetComparisonValue(_comparisonProperty, validationContext);
if (ErrorMessage == null && ErrorMessageResourceName == null)
{
ErrorMessage = "Amount is large";
}
else
{
ErrorMessage = string.Format(ErrorMessage ?? "", comparisonValue);
}
return currentValue >= comparisonValue
? new ValidationResult(ErrorMessage)
: ValidationResult.Success;
}
public override string FormatErrorMessage(string name)
{
return base.FormatErrorMessage(name);
}
private decimal GetComparisonValue(string comparisonProperty, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(comparisonProperty);
if (property == null)
throw new ArgumentException("Not Found!");
var comparisonValue = (decimal)property.GetValue(validationContext.ObjectInstance);
return comparisonValue;
}
}
答案 0 :(得分:1)
这是因为您正在使用ErrorMessage
来设置string.Format(ErrorMessage ?? "", comparisonValue);
的值。 ErrorMessage
是[AmountShouldBeLessOrEqual(nameof(MaxAmount), ErrorMessage = "Your amount should be less than {0}")]
中的值,您不应在IsValid
期间更改它。
尝试在IsValid
中定义作用域变量以存储格式化的错误消息。
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string error = "";
var currentValue = (decimal)value;
var comparisonValue = GetComparisonValue(_comparisonProperty, validationContext);
if (ErrorMessage == null && ErrorMessageResourceName == null)
{
ErrorMessage = "Amount is large";
}
else
{
error = string.Format(ErrorMessage ?? "", comparisonValue);
}
return currentValue >= comparisonValue
? new ValidationResult(error)
: ValidationResult.Success;
}