C# DataAnnotations and resource files - why no simple constructor?
I'm using DataAnnotions in a ASP.NET MVC application for validate my input models. If I want to use resource files for the error messages, then I have to specify these with named parameters, like so:
[Required(
ErrorMessageResourceType = typeof(Validation),
ErrorMessageResourceName = "NameRequired")]
Since I use this in a bunch of files, I thought, it would be much easier (and more readable) if I could use a constructor like this:
[Required(typeof(Validation), "NameRequired")]
If I write my own custom validation attribute I could implement such a "simple constructor":
public class MyCustomValidationAttribute : ValidationAttribute
{
public MyCustomValidationAtt开发者_如何学编程ribute(Type resourceType, string resourceName)
{
base.ErrorMessageResourceType = resourceType;
base.ErrorMessageResourceName = resourceName;
}
}
Am I missing something here or want us Microsoft's DataAnnotations team just to write some extra lines? :-)
EDIT:
Just for clarification: I have a resource file called "Validation.resx".
I hear you and feel your pain. We have a database with thousands of items that need data annotations.
One option is to use resource files. It may seem like even more work at first, but you can reuse resources for simple things like "Name required". See this StackOverflow item for some leads.
You could have a look at this Github extension which results in much cleaner code: http://haacked.com/archive/2011/07/14/model-metadata-and-validation-localization-using-conventions.aspx
精彩评论