Data Annotations. How to replace range values ​​with Web.Config values ​​in MVC3?

How to replace range values ​​with Web.Config values ​​in MVC3?

[Range(5, 20, ErrorMessage = "Initial Deposit should be between $5.00 and $20.00")
public decimal InitialDeposit { get; set; }

web.config:

<add key="MinBalance" value="5.00"/>
<add key="MaxDeposit" value="20.00"/>
+5
source share
3 answers

You will need to create your own attribute that inherits from RangeAttributeand implements IClientValidatable.

    public class ConfigRangeAttribute : RangeAttribute, IClientValidatable
    {
        public ConfigRangeAttribute(int Int) :
            base
            (Convert.ToInt32(WebConfigurationManager.AppSettings["IntMin"]),
             Convert.ToInt32(WebConfigurationManager.AppSettings["IntMax"])) { }

        public ConfigRangeAttribute(double Double) :
            base
            (Convert.ToDouble(WebConfigurationManager.AppSettings["DoubleMin"]),
             Convert.ToDouble(WebConfigurationManager.AppSettings["DoubleMax"])) 
        {
            _double = true;
        }

        private bool _double = false;

        public override string FormatErrorMessage(string name)
        {
            return String.Format(ErrorMessageString, name, this.Minimum, this.Maximum);
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(this.ErrorMessage),
                ValidationType = "range",
            };
            rule.ValidationParameters.Add("min", this.Minimum);
            rule.ValidationParameters.Add("max", this.Maximum);
            yield return rule;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
                return null;

            if (String.IsNullOrEmpty(value.ToString()))
                return null;

            if (_double)
            {
                var val = Convert.ToDouble(value);
                if (val >= Convert.ToDouble(this.Minimum) && val <= Convert.ToDouble(this.Maximum))
                    return null;
            }
            else
            {
                var val = Convert.ToInt32(value);
                if (val >= Convert.ToInt32(this.Minimum) && val <= Convert.ToInt32(this.Maximum))
                    return null;
            }

            return new ValidationResult(
                FormatErrorMessage(this.ErrorMessage)
            );
        }
    }

Usage example:

[ConfigRange(1)]
public int MyInt { get; set; }

[ConfigRange(1.1, ErrorMessage = "This one has gotta be between {1} and {2}!")]
public double MyDouble { get; set; }

The first example will return a default error message, and the second will return your error message. Both will use the range values ​​defined in web.config.

+7
source

, . , , - RangeAttribute web.config . -

public class RangeFromConfigurationAttribute : RangeAttribute
{
    public RangeFromConfigurationAttribute()
        : base(int.Parse(WebConfigurationManager.AppSettings["MinBalance"]), int.Parse(WebConfigurationManager.AppSettings["MaxDeposit"]))
    {

    }
}

, :)

+4

, ConfigRange , . , web.config, app.config , , ?

public static class RangeReader
{
    public static double Range1 
    {
        // Replace this with logic to read from config file
        get { return 20.0d; } 
    }        
}

:

[Range(ConfigReader.Range1, 25.0d)]

, , , , , .

+1

All Articles