是否有人将Range属性扩展为能够拥有变量范围?
我有类似的需求,但我无法做到这一点:
public class YearRangeAttribute : RangeAttribute
{
public YearRangeAttribute()
: base(typeof(DateTime), DateTime.Now.AddYears(-100).Year.ToString(), DateTime.Now.AddYears(-14).Year.ToString()) { }
}
当页面呈现给浏览器时,页面上没有任何内容。
有什么想法吗?
TIA
答案 0 :(得分:2)
# public class YearRangeAttribute : RangeAttribute
# {
#
#
#
# public YearRangeAttribute()
# : base(DateTime.Now.AddYears(-100).Year, DateTime.Now.AddYears(-16).Year) { }
#
#
#
# }
并在Global.asax.cs上:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(YearRangeAttribute), typeof(RangeAttributeAdapter));
干杯
Lizet
答案 1 :(得分:1)
以下是工作示例:
public class PermittedYearRangeAttribute : RangeAttribute
{
public PermittedYearRangeAttribute()
: base(1900, DateTime.Now.AddYears(-50).Year)
{
ErrorMessage = string.Format("Year must be between 1900 and {0}", DateTime.Now.AddYears(-50).Year);
}
}
在Global.asax.cs
Application_Start()
方法中添加以下行
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(PermittedYearRangeAttribute), typeof(RangeAttributeAdapter));
在模型装饰属性中:
[Required(ErrorMessage = "Please enter year")]
[PermittedYearRange]
public int Year { get; set; }
呈现的HTML:
<input class="tooltip form-control input dob--input input-validation-error" data-val="true" data-val-number="The field Year must be a number." data-val-range="Year must be between 1900 and 1965" data-val-range-max="1965" data-val-range-min="1900" data-val-required="Please enter year" id="Year" maxlength="4096" name="Year" placeholder="YYYY" tabindex="" type="text" value="0">