假设我有这个视图模型:
public class MyModel
{
[Range(0, 999, ErrorMessage = "Invalid quantity")]
public int Quantity { get; set; }
}
现在,对于该模型的特定实例,有效值的范围将发生变化:有些可能不为 0,有些可能不高于 5。有效范围的最小/最大值来自数据库,并且可以随时更改。
如何动态更改 RangeAttribute 的最小/最大属性?或者验证我的场景的最佳方法是什么?
类似的事情可能更符合您的需求......
视图模型:
public class ViewModel
{
public DateTime MinDate {get; set;}
public DateTime MaxDate {get; set;}
[DynamicRange("MinDate", "MaxDate", ErrorMessage = "Value must be between {0} and {1}")]
public DateTime Date{ get; set; }
}
图书馆类或其他地方:
public class DynamicRange : ValidationAttribute, IClientValidatable
{
private readonly string _minPropertyName;
private readonly string _maxPropertyName;
public DynamicRange(string minPropName, string maxPropName)
{
_minPropertyName = minPropName;
_maxPropertyName = maxPropName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var minProperty = validationContext.ObjectType.GetProperty(_minPropertyName);
var maxProperty = validationContext.ObjectType.GetProperty(_maxPropertyName);
if(minProperty == null)
return new ValidationResult(string.Format("Unknown property {0}", _minPropertyName));
if (maxProperty == null)
return new ValidationResult(string.Format("Unknown property {0}", _maxPropertyName));
var minValue = (int) minProperty.GetValue(validationContext.ObjectInstance, null);
var maxValue = (int) maxProperty.GetValue(validationContext.ObjectInstance, null);
var currentValue = (int) value;
if (currentValue <= minValue || currentValue >= maxValue)
{
return new ValidationResult(string.Format(ErrorMessage, minValue, maxValue));
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ValidationType = "dynamicrange",
ErrorMessage = ErrorMessage
};
rule.ValidationParameters["minvalueproperty"] = _minPropertyName;
rule.ValidationParameters["maxvalueproperty"] = _maxPropertyName;
yield return rule;
}
From: MVC 动态值的不引人注目的范围验证
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)