从代码中添加和删除数据注释
是否可以从代码方面添加和删除 DataAnnotations,特别是 [requried]?我的问题是,我想让用户能够在 CRUD 应用程序中保存不完整的表单,但同时使用 DataAnnotations 验证的功能。
如果这是不可能的,我能采取的最佳方法是什么?
Is there away to add and remove DataAnnotations, in particular the [requried], from the code side of things? My problem is that I want to give the user the ability to save an incomplete form in our CRUD applications but at the same time use the power of the DataAnnotations validation.
If this is not possible, what is the best way I can go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在模型上保留 DataAnnotation 属性,然后根据需要从代码中手动清除验证错误。它可能看起来像这样:
You can keep the DataAnnotation attributes on your model and then just manually clear the validation errors as needed from code. It might look something like this:
不可能动态添加、删除或修改 DataAnnotations,因为它们是属性。属性是类型的一部分,不能在运行时更改。
您可以按照 Larsenal 的建议使用 ModelState,前提是:
It is impossible to add, remove or modify DataAnnotations dynamically since they are Attributes. Attributes are part of the type and can't be changed during runtime.
You could use ModelState as Larsenal suggested provided that: