Validating PART of the model with ASP.NET MVC & Data Annotations
We have our POCO classes setup using Data Annotations.
For one of these classes, we invole more than one view for the user to populate all of their data. For example if it were a class with username and password as properties we would on the first page get the user to specify their username and on the second page specify their password.
Now, if i use the full POCO class (which requires that both username & password are supplied) then when we ask ModelState.IsValid were get false since the password hasn't yet been supplied, but we know that the password is going to be supplied on the next page!
Is there a generic way for us to validate those elements of the model for which values should have been provided rather than the whole Model? I know that i can remove the errors for individual items from the ModelState.
I know that we could separate out the model elements to have separate models for each page part of the entry that is being performed but this feels like we are changing the underlying class to fit more with the view.
Regards
Jamie
I believe the approach here by Steve deals with this
http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/
in essence he filters out those keys for which there are no incoming values.
Try putting the validation on the ViewModel classes. Each view will have its own ViewModel class. One with the username, the other with the password. Don't use the model until you gathered all the data you need.
链接地址: http://www.djcxy.com/p/56588.html上一篇: 模型验证数据注释的哪一层?