Data Annotations for a subset of properties
I've been reading up on Data Annotations (ie 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.
链接地址: http://www.djcxy.com/p/9694.html上一篇: 在asp.net mvc 2.0中进行模型状态验证
下一篇: 数据注释属性的一个子集