开发者

Data Annotations for a subset of properties

开发者 https://www.devze.com 2023-01-13 20:17 出处:网络
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.

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消