tags:

views:

38

answers:

1

In my domain Model I have a Person object that has a number of properties which I have decorated with Validation Metadata:

[Required(ErrorMessage = "First Name Required")]
public string FirstName { get; set; }

[Required(ErrorMessage = "Age Required")]
public int Age { get; set; }

My Controller returns a collection of Persons to the view so that the user can fill in their details. However only the first Person needs to supply an age so I only need to validate the age for the first Person in the collection.

However, due to the Validation metadata on the Age property, the model validation is failing because the age is not being supplied for the other Persons in the collection.

Is there any way to switch off validation for the other Person objects in the collection?

Or do I need to rearrange my Models.

A: 

My instinct would be to decorate the action or controller with a custom attribute to intercept the validation of a request. For example, in the ValidateOnlyFirstPersonInCollection attribute, you can override the OnActionExecuting method as follows:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var modelState= filterContext.Controller.ViewData.ModelState;
    var incomingValues = filterContext.Controller.ValueProvider;
    // depending on how your app works, 
    // ascertain the Condition that applies when you want the       age field validated
    // Then:
    var keys = modelState.Keys.Where(x => ![Condition]);
   foreach(var key in keys) // These keys don't satisfy the Condition for validation
     modelState[key].Errors.Clear();
}

Your problem is now reduced to figuring out the condition. The above gives you a rough idea. For more details, see Steve Sanderson's book on MVC 2, page 486.

awrigley