【转】ASP.NET MVC 3 Service Location, Part 6: Model Validation
Model Validators
ASP.NET MVC 2 introduced an extensible model validation system where developers could implement a class which derived from ModelValidatorProvider to influence the validation process on both the client-side and server-side. In ASP.NET MVC 3, we have made these validator providers findable via the dependency resolver.
Disclaimer
This blog post talks about ASP.NET MVC 3 Beta, which is a pre-release version. Specific technical details may change before the final release of MVC 3. This release is designed to elicit feedback on features with enough time to make meaningful changes before MVC 3 ships, so please comment on this blog post or contact me if you have comments.
Writing a Validator Provider
For an example implementation of ModelValidatorProvider, see my blog post: Enterprise Library Validation example for ASP.NET MVC 2.
Location: ModelValidatorProvider
This is a “multiply registered” style service introduced in MVC 2. The static registration point for this service is atModelValidatorProviders.Providers for non-DI users.
Model validator providers inspect models, and return validators that ensure that the models are valid. They also participate in the client-side validation by returning client “validation hints” consumed by JavaScript.
The logic in ModelValidatorProviderCollection (which implements ModelValidatorProviders.Providers) was updated to consult the dependency resolver, calling GetServices(typeof(ModelValidatorProvider)) and adding any services found to the list of statically registered service. Validator providers all collaborate to potentially validate a model value, so the ordering of validator providers is not important. Every provider will get an opportunity to provide validators.
What’s Next?
Next up we’ll talk about Model Metadata.