如何将 DisplayName 置于 ErrorMessage 格式中
我有这样的内容:
[DisplayName("First Name")]
[Required(ErrorMessage="{0} is required.")]
[StringLength(50, MinimumLength = 10, ErrorMessage="{0}'s length should be between {2} and {1}.")]
public string Name { get; set; }
我想要以下输出:
- 需要名字。
- 名字的长度应该在 10 到 50 之间。
使用 ASP.NET MVC2 错误摘要时它可以工作,但是当我尝试手动验证它时,如下所示:
ValidationContext context = new ValidationContext(myModel, null, null);
List<ValidationResult> results = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(myModel, context, results, true);
结果是:
- 名称是必需的。
- 名称长度应在 10 到 50 之间。
有什么问题吗?谢谢。
I have something like this:
[DisplayName("First Name")]
[Required(ErrorMessage="{0} is required.")]
[StringLength(50, MinimumLength = 10, ErrorMessage="{0}'s length should be between {2} and {1}.")]
public string Name { get; set; }
I want to have the following output:
- First Name is required.
- First Name's length should be between 10 and 50.
It is working when using ASP.NET MVC2 Error Summary, but when I try to validate it manually, like this:
ValidationContext context = new ValidationContext(myModel, null, null);
List<ValidationResult> results = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(myModel, context, results, true);
The results are:
- Name is required.
- Name's length should be between 10 and 50.
What's wrong? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要使用(或可能结合使用)
[DisplayName]
属性,而是使用System.ComponentModel.DataAnnotations
中的[Display]
属性。填充其Name
属性。这样,您就可以将内置验证属性或自定义属性与
ValidationContext
的DisplayName
结合使用。例如,
Instead of (or perhaps in conjunction with) using the
[DisplayName]
attribute, use the[Display]
attribute inSystem.ComponentModel.DataAnnotations
. Populate itsName
property.With that, you can use built-in validation attributes or custom attributes with
ValidationContext
'sDisplayName
.e.g.,
嗯,我想我做到了。
我必须创建另一个像这样的属性:
我的模型是:
值得庆幸的是,这个 DataAnnotation 是可扩展的。
Well, I think I did it.
I had to create another attribute like this:
And my model is:
Thankfully this DataAnnotation is extensible.