views:

38

answers:

1

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?

+2  A: 

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.

Necros
Being new to ASP.NET MVC I'm not entirely sure about the validity of "every view should have it's own view model". In fact, in the comments of the Sanderson link I provided above, there are folks debating that exact phrase. Can you provide links to articles that discuss this further? I noticed the Visual Studio template seemingly follows this (i.e. ChangePasswordModel and LogOnModel) but I can't find much information on it.
Mayo
@Mayo, because each of those views means a totally different thing in a different context. They do not share inheritance or even a relationship and are only similar in that they share some properties. http://domaindrivendesign.org/node/91
jfar
Thanks jfar and Necros - I think what I'm looking for is the act of having a domain model and a view model.
Mayo