gpt4 book ai didi

asp.net-mvc - 数据注释 - 如何在 MVC3 中用 Web.Config 值替换 Range 值?

转载 作者:行者123 更新时间:2023-12-04 16:48:46 25 4
gpt4 key购买 nike

如何用 MVC3 中的 Web.Config 值替换 Range 值?

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

网络配置:
<add key="MinBalance" value="5.00"/>
<add key="MaxDeposit" value="20.00"/>

最佳答案

您将需要创建一个继承自 RangeAttribute 的自定义属性。并实现 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)
);
}
}

用法示例:
[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; }

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

关于asp.net-mvc - 数据注释 - 如何在 MVC3 中用 Web.Config 值替换 Range 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7843334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com