数据注释和资源不能很好地发挥作用 [英] DataAnnotations and Resources don't play nicely

查看:125
本文介绍了数据注释和资源不能很好地发挥作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MVC2应用程序中使用数据注释,并且在尝试将RESX文件资源用于错误消息时有些气disc.

I'm using dataannotations in an MVC2 app and am a little discouraged when trying to use RESX file resources for error messages.

我尝试了以下操作,但始终收到异常属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式"

I've tried the following but keep getting the exception "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type"

[Required(ErrorMessage = Resources.ErrorMessages.Required)]
[Required(ErrorMessageResourceName = Resources.ErrorMessages.Required,
          ErrorMessageResourceType = typeof(Resources.ErrorMessages)]

除非将ErrorMessageResourceName替换为"Required"而不是Resources.ErrorMessages.Required,否则我会一直收到该错误消息.

I keep getting that error message unless I replace ErrorMessageResourceName with "Required" instead of Resources.ErrorMessages.Required.

有人可以告诉我我是否这样做正确?

Can anyone tell me if I'm doing this right?

推荐答案

是的,最后您所做的基本上是正确的. ErrorMessageResourceName接受名称的含义,即资源的名称,而不是资源本身.

Yes, what you're doing at the end is basically correct. The ErrorMessageResourceName takes what the name implies, the name of a resource, not the resource itself.

Resources.ErrorMessages.Required指向 actual (本地化)错误消息(资源).资源的名称只是必需",而资源管理器的 type (用于ErrorMessageResourceType)是包含该资源的类,在这种情况下Resources.ErrorMessages类.

Resources.ErrorMessages.Required points to the actual (localized) error message (resource). The name of the resource is simply "Required", and the type of the resource manager (used for ErrorMessageResourceType) is the class that contains that resource, in this case the Resources.ErrorMessages class.

所以您的声明应如下所示:

So your declaration should look like this:

[Required(ErrorMessageResourceType = typeof(Resources.ErrorMessages),
    ErrorMessageResourceName = "Required")]
public string Something { get; set; }

这篇关于数据注释和资源不能很好地发挥作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆