ASP.NET MVC 2 中的 DataAnnotations - 阻止 MVC 将RequiredAttribute 应用于不可为空的 DateTime 等属性

发布于 2024-08-26 05:11:15 字数 337 浏览 7 评论 0原文

我正在尝试创建一个自定义版本的RequiredAttribute来替换内置版本,并且我已经让它适用于具有字符串值的属性,但是对于例如DateTime或整数的属性,默认的RequiredAttribute似乎会自动应用(如果该属性不可为空!)

我的问题是我希望能够使用我的自定义必需验证器根据需要指定 DateTime 属性,该验证器从资源文件中获取错误消息(我不想告诉RequiredAttribute资源文件的类型和每次应用它时的密钥,这就是我制作自定义文件的原因。)

如何防止框架将所需的属性应用于 DateTime 和 int 等类型的属性 将它们更改为可为空。

谢谢

Im trying to create a custom version of the RequiredAttribute to replace the built in one and I've got it working for properties that have strings values, but with properties that are DateTime or integer for example, the default RequiredAttribute seems to be applied automatically (IF the property is not nullable!)

My problem is that i want to be able to specify a DateTime property as required using my custom required validator which gets the error message from a resources file (I don't want to have to tell the RequiredAttribute the type of the resource file and the key every time i apply it. That is why I'm making a custom one.)

How can i prevent the framework from applying the required attribute to properties of type DateTime and int etc without changing them to nullable.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜警司 2024-09-02 05:11:15

找到了!我将其放入 Global.asax.cs 文件中

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

DataAnnotationsModelValidatorProvider 类有一个名为“AddImplicitRequiredAttributeForValueTypes”的静态属性,默认情况下该属性必须为 true,并将其设置为 false 解决了该问题。

(对于任何尝试做同样的事情来找到此条目的人,我正在记录它 此处

Found it! I put this in the Global.asax.cs file

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

The DataAnnotationsModelValidatorProvider class has a static property called "AddImplicitRequiredAttributeForValueTypes" which by default must be true, and setting it to false fixed the problem.

(For anyone trying to do the same sort of things that finds this entry, I'm documenting it here)

电影里的梦 2024-09-02 05:11:15

我安装了 RTM,但没有 AddImplicitRequiredAttributeForValueTypes 属性...

I have RTM installed and dont have the AddImplicitRequiredAttributeForValueTypes property...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文