views:

265

answers:

1

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?

+4  A: 

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; }
Aaronaught
Can I just use the ErrorMessage property instead? I prefer strongly typed....
devlife
@devlife: No. Not if you want localization. That's exactly what the resource properties are for. In fact, this is how it is with *any* localization, at some point in the chain you're going to have to look up a resource string based on the name, that's just how externalized resources work. And this is still "strongly-typed" based on the resource class, you just don't have compile-time safety on the resource name itself. If you want that, just create a class like `ResourceNames` with lines like `public const string Required = "Required"`, then you can specify those as the resource names.
Aaronaught