属性子集的数据注释
我一直在阅读数据注释(即 Scott Guthrie 的博客文章),我对将验证逻辑放在一个地方的概念感到非常兴奋。
当提示用户输入与给定类关联的属性子集时,是否有人能够成功使用此技术?
例如(伪代码)...
public class Person
{
[Required]
public string Name
[Required]
public string Email
}
然后假设您有一个仅显示带有名称的表单的视图。该视图的 HttpPost 控制器中的 ModelState.IsValid 值始终为 false,因为电子邮件是必需的且缺失。
我考虑过拥有单独的模型,一个用于仅需要名称的部分,另一个用于需要名称和电子邮件的部分,但随后我打破了 DRY 原则,因为我将在两个模型中使用名称验证逻辑地方。
有什么建议吗?可以让数据注释以这种方式工作吗?我应该只上两个单独的课程吗?也许是 CustomValidationAttribute 在确定是否需要邮箱吗?
I've been reading up on Data Annotations (i.e. Scott Guthrie's blog post) and I am thrilled about the concept of having validation logic in one place.
Has anyone been able to use this technique successfully when prompting the user to enter a subset of the properties associated with a given class?
For example (pseudocode)...
public class Person
{
[Required]
public string Name
[Required]
public string Email
}
Then let's say you have a view that displays a form only with Name. The value of ModelState.IsValid within the HttpPost controller for that view will always be false because Email is required and missing.
I've thought about having separate models, one for the part that requires only Name, and another for the part that requires both Name and Email, but then I'm breaking the principle of DRY because I'll have Name validation logic in two places.
Any suggestions? Can one get Data Annotations working in this manner? Should I simply have two separate classes? Maybe a CustomValidationAttribute that checks a flag before determining if Email is required?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每个视图都应该有它自己的视图模型。有时您可以重用某些现有的视图模型 - 但现在却不能。
仅当这些属性采用一种形式时,我才会创建自定义属性,有时两者都是必需的,有时仅需要其中之一。如果您有单独的视图,我会制作另一个视图模型。
Every view should have it's own view model. There are times when you can reuse some existing view models - this is the time that you can't.
I would create custom attribute only if those properties were in one form, and sometimes both were required and sometimes only one of them was required. If you have separate views I would make another view model.