Providing mutable value in RangeAttribute?

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?

+4
source share
3 answers

You can create a custom attribute for this, 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 ...

+6
source

Here is my version based on the previous answer (but working both on the client side and on the server):

  [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 example:

 [RangeYearToCurrent(1995, ErrorMessage = "Invalid Date")] public int? Year { get; set; } 
+4
source

You cannot do this with attributes.

Attributes are always compiled directly and are intended as metadata, not "executable code." Thus, the parameter in the attribute must always be fully known at compile time - that is: a constant value.

Attempting to use a value that requires a run-time expression will not be performed on the attribute. This is true for all attributes, not just the RangeAttribute attribute.

+2
source

Source: https://habr.com/ru/post/1338301/


All Articles