I have a ViewModel class like this:
class CaseModel {
public Boolean ClientPresent { get; set; }
public ClientModel Client { get; set; }
}
class ClientModel {
[Required]
public String FirstName { get; set; }
[Required]
public String LastName { get; set; }
}
The view page consists of a <input type="checkbox" name="ClientPresent" />
and a Html.EditorFor( m => m.Client )
partial view.
The idea being that when the user if providing information about a case (a business-domain object) that they can choose to not specify any information about the client (another biz object) by unchecking the ClientPresent box.
I want ASP.NET MVC to not perform any validation of the child ClientModel object - however the CaseModel.Client property is automatically populated when a form is POSTed back to the server, but because FirstName
and LastName
aren't (necessarily) provided by the user it means it fails the [Required]
validation attributes, consequently ViewData.ModelState.IsValid
returns false and the user gets a validation error message.
How can I get it so CaseModel.Client
will not be validated if CaseModel.ClientPresent
is false?
Note that ClientModel
is a fully independent ViewModel class and is used elsewhere in the application (such as in the ClientController class which lets the user edit individual instances of Clients).