扩展MVC 2中的RangeAttribute(DataAnnotations命名空间),使其具有基于今天日期的可变日期范围

时间:2010-08-17 21:35:35

标签: model-view-controller attributes range

是否有人将Range属性扩展为能够拥有变量范围?

我有类似的需求,但我无法做到这一点:

public class YearRangeAttribute : RangeAttribute
    {
        public YearRangeAttribute()
            : base(typeof(DateTime), DateTime.Now.AddYears(-100).Year.ToString(), DateTime.Now.AddYears(-14).Year.ToString()) { }

    }

当页面呈现给浏览器时,页面上没有任何内容。

有什么想法吗?

TIA

2 个答案:

答案 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">