DataAnnotations and Resources don't play nicely

﹥>﹥吖頭↗ 提交于 2019-12-29 06:49:13

问题


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

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

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?


回答1:


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


来源:https://stackoverflow.com/questions/2451150/dataannotations-and-resources-dont-play-nicely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!