When I do the following:
`[Range(1910, DateTime.Now.Year)]
public int Year { get; set; }`
I get the following error:
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
Any ideas why?开发者_JAVA百科
You could build for this a custom attribute something like RangeYearToCurrent
in which you specify the current year
public class RangeYearToCurrent : RangeAttribute
{
public RangYearToCurrent(int from)
: base(typeof(int), from, DateTime.Today.Year) { }
}
untested...
Here's my version, based on the previous answer (but working both client/server side):
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class RangeYearToCurrent : RangeAttribute,IClientValidatable {
public RangeYearToCurrent(int from) : base(from, DateTime.Today.Year) { }
#region IClientValidatable Members
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rules = new ModelClientValidationRangeRule(this.ErrorMessage, this.Minimum, this.Maximum);
yield return rules;
}
#endregion
}
Usage Exemple :
[RangeYearToCurrent(1995, ErrorMessage = "Invalid Date")]
public int? Year { get; set; }
You cannot do this with attributes.
Attributes are always compiled directly in, and are intended as meta data, not "executable code". As such, the parameter in an attribute must always be known completely at compile time - ie: a constant value.
Trying to use a value that requires a runtime expression will fail in an attribute. This is true in all attributes, not just RangeAttribute.
精彩评论