C# DataAnnotations 和资源文件 - 为什么没有简单的构造函数?
我在 ASP.NET MVC 应用程序中使用 DataAnnotions 来验证我的输入模型。如果我想使用资源文件来显示错误消息,那么我必须使用命名参数来指定它们,如下所示:
[Required(
ErrorMessageResourceType = typeof(Validation),
ErrorMessageResourceName = "NameRequired")]
由于我在一堆文件中使用它,我想,如果我可以使用这样的构造函数:
[Required(typeof(Validation), "NameRequired")]
如果我编写自己的自定义验证属性,我可以实现这样一个“简单的构造函数”:
public class MyCustomValidationAttribute : ValidationAttribute
{
public MyCustomValidationAttribute(Type resourceType, string resourceName)
{
base.ErrorMessageResourceType = resourceType;
base.ErrorMessageResourceName = resourceName;
}
}
我是否在这里遗漏了一些东西,或者希望我们 Microsoft 的 DataAnnotations 团队只编写一些额外的行? :-)
编辑:
只是为了澄清:我有一个名为“Validation.resx”的资源文件。
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 MyCustomValidationAttribute(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".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我听到你的声音并感受到你的痛苦。我们有一个数据库,其中有数千个需要数据注释的项目。
一种选择是使用资源文件。乍一看,这似乎需要更多工作,但您可以重复使用资源来完成“需要名称”等简单的事情。请参阅此StackOverflow 项目以获取一些线索。
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.
你可以看看这个 Github 扩展,它会产生更清晰的代码: http://haacked.com/archive/2011/07/14/model-metadata-and-validation-localization-using-conventions.aspx
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