Asp.net mvc 数据注释-如何用MVC3中的Web.Config值替换范围值?

Asp.net mvc 数据注释-如何用MVC3中的Web.Config值替换范围值?,asp.net-mvc,asp.net-mvc-3,Asp.net Mvc,Asp.net Mvc 3,如何用MVC3中的Web.Config值替换范围值 [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"/&g

如何用MVC3中的Web.Config值替换范围值

[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"/>

您将无法在属性的属性声明中执行此操作,因为需要在编译时知道值。我能看到的最简单的方法是从
RangeAttribute
派生属性类,并将属性值设置为来自派生类中的web.config。差不多

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

    }
}

不过,您可能想想出一个更好的名称:)

您需要创建一个自定义属性,该属性继承自
RangeAttribute
,并实现
IClientValidable

    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)
            );
        }
    }

第一个示例将返回默认错误消息,第二个示例将返回自定义错误消息。两者都将使用web.config中定义的范围值。

在这里大声思考,但ConfigRange属性指示必须存在配置才能工作。您不能编写一个静态类,从web.config、app.config或任何您认为合适的地方读取您的值,然后在现有的range属性中使用该静态类吗

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)]

我知道静态类很糟糕,不这样做可能有一个很好的理由,但我想我会试试。

非常感谢您的重复。我只是用上面的代码创建了一个类,但它不起作用。我是不是遗漏了什么?我会看看我是否能举出一个例子,尽管Coursellorben的代码看起来很有效-@Russ-Cam,很高兴有人注意到我的贡献。虽然你仍然有好吃的东西再次感谢Russ Cam。顾问本给出的解决方案非常有效!我对视图模型没有任何编译错误,但没有机会通过向视图传递视图模型来测试这一点。你还记得为什么这不起作用吗?我会再试一次,让你知道错误消息。谢谢我遇到编译错误:属性参数必须是常量表达式、类型表达式或属性参数类型的数组创建表达式。非常感谢。^>谢谢,祝你好运。@1962,好吧,与其说是天才。我快速查看了我的代码,发现我的服务器端验证测试是错误的:^O我修复了
IsValid()
函数中不正确的行。请确保应用这些更改。
[Range(ConfigReader.Range1, 25.0d)]