我创建了以下自定义ValidationAttribute: public class DateRangeAttribute : ValidationAttribute, IClientValidatable { public DateTime MinimumDate = new DateTime(1901, 1, 1); public DateTime MaximumDate = new DateTime(2099, 12, 31);
public class DateRangeAttribute : ValidationAttribute, IClientValidatable { public DateTime MinimumDate = new DateTime(1901, 1, 1); public DateTime MaximumDate = new DateTime(2099, 12, 31); public DateRangeAttribute(string minDate, string maxDate, string errorMessage) { MinimumDate = DateTime.Parse(minDate); MaximumDate = DateTime.Parse(maxDate); ErrorMessage = string.Format(errorMessage, MinimumDate.ToString("MM/dd/yyyy"), MaximumDate.ToString("MM/dd/yyyy")); } }
我想在我的MVC4视图模型中使用如下:
[DateRange(Resources.MinimumDate, Resources.MaximumDate, "Please enter a date between {0} and {1}")]
Resources是基于存储在SQL数据库中的一组选项生成的资源类.上述两个资源属性的生成代码的简化版本是:
public class Resources { public const string MinimumDate = "PropMinimumDate"; public static string PropMinimumDate { get { return "12/15/2010" } } public const string MaximumDate = "PropMaximumDate"; public static string PropMaximumDate { get { return "12/15/2012" } } }
虽然我不明白它是如何工作的,但我确实理解ValidationAttributes中资源的典型使用会自动将Resources.MinimumDate映射到PropMinimumDate并返回值“12/15/2010”.
我无法弄清楚的是如何自己手动进行程序化跳跃,以便我可以将两个日期值传递到我的自定义ValidatorAttribute中.如目前编码,“PropMinimumDate”和“PropMaximumDate”是传递到DateRangeAttribute的构造函数中的minDate和maxDate参数值(分别).
如果我试试
[DateRange(Resources.PropMinimumDate, Resources.PropMaximumDate, "Please enter a date between {0} and {1}")]
我收到编译错误:
属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式
有没有办法完成这项任务,还是我尝试了不可能的事情?
您需要将资源类的Type作为参数,然后使用反射来获取属性值.public class DateRangeAttribute : ValidationAttribute, IClientValidatable { public DateTime MinimumDate = new DateTime(1901, 1, 1); public DateTime MaximumDate = new DateTime(2099, 12, 31); private Type _resourceType; public DateRangeAttribute(string minDate, string maxDate, string errorMessage, Type resourceType) { _resourceType = resourceType; var minDateProp = _resourceType.GetProperty(minDate, BindingFlags.Static | BindingFlags.Public); var minDateValue = (string) minDateProp.GetValue((object) null, (object[]) null)); MinimumDate = DateTime.Parse(minDateValue); // similarly get the value for MaxDate ErrorMessage = string.Format(errorMessage, MinimumDate.ToString("MM/dd/yyyy"), MaximumDate.ToString("MM/dd/yyyy")); } }
例如
[DateRange(Resources.MinimumDate, Resources.MaximumDate, "Please enter a date between {0} and {1}", typeof(Resources))]