views:

275

answers:

2

I'm using Data Annotations with ASP.NET MVC 2 as demonstrated in this post:

http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

Everything works fine when creating / updating an entity where all required property values are specified in the form and valid.

However, what if I only want to update some of the fields? For example, let's say I have an Account entity with 20 fields, but I only want to update Username and Password?

ModelState.IsValid validates against all the properties, regardless of whether they are referenced in the submitted form.

How can I get it to validate only the fields that are referenced in the form?

+2  A: 

The recommended practice is to use a model specific to each view. In your case this this would be a model with only username and password properties. When the user submits the form, you would map the properties to your actual domain object in the controller. For this I use Automapper to simplify the mapping. This does mean you'd need to set your validation rules in each view model though.

Simon Bartlett
Thanks. Does Automapper negate the need to respecify the validation rules within the view specific model?
Robert Morgan
No, you'll still need to respecify the validation rules in your view specific models.
Simon Bartlett