在的String.format数据注释验证属性 [英] string.Format in Data Annotation Validation Attributes
问题描述
有没有办法使用格式化字符串而不是直接常数设置数据注解的消息,
Is there any way to set Data Annotation messages using formatted string instead of direct constant,
我需要设置必填字段的ErrorMessage像下面code,但它给了我一个错误。
I need to set required field ErrorMessage like in following code, but it gives me an error.
[Required(ErrorMessage = string.Format(SystemMessages.Required, "First Name"))]
public string FirstName { get; set; }
SystemMessages
是一个常数文件,它具有以下code,
SystemMessages
is a constant file and it has following code,
public const string Required = "{0} is required.";
有什么办法来设置这样的属性?
Is there any way to set attributes like this?
推荐答案
的String.Format
结果不是编译时间常数,不能蜜蜂编译器进行评估。属性值限制为恒前pression,属性参数类型的typeof前pression或数组创建前pression
。
string.Format
result is not a compile time constant and can't bee evaluated by the compiler. Attribute values are limited to constant expression, typeof expression or array creation expression of an attribute parameter type
.
更正式,你可以的 MSDN 。格式化字符串不符合其中任何一个,它们分别是:
More formally, you can find description of limitations at msdn. Formatting a string doesn't fit any of them, which are:
- 简单类型(BOOL,BYTE,CHAR,short,int和长,float和双)
- 字符串
- 的System.Type
- 枚举
- 对象(参数类型对象的属性参数必须是以上类型的酮一个恒定值。)
- 上述任何类型的一维阵列
目前最好的,你可以尝试类似于:
At best you can try something similar to:
[Required(ErrorMessage = "First Name" + Required)]
public string FirstName { get; set; }
public const string Required = " is required.";
这篇关于在的String.format数据注释验证属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!