0

In my business domain, a "User" entity is associated with a single "Person" entity (so the User instance contains security/login information, but the Person entity contains the person's human contact information).

My ViewModel looks like this:

class UserViewModel {
    [Required]
    public String UserName { get; set; }

    public Int64 PersonId { get; set; }
    public PersonViewModel Person { get; set; }

    public Boolean PersonViewModelIsNew { get; set; }
}

class PersonViewModel {
    [Required]
    public String FirstName;
    [Required]
    public String LastName;
    // etc
}

The web-page allows the visitor to edit a User such that they can replace the User's Person information with either a brand-new Person instance, or an existing Person pulled from the database.

Attached is a screenshot of the form:

Screenshot of the form

The idea is that if the "Another employee" radio-button (maps to "UserViewModel.PersonViewModelIsNew" property) is selected then the validation of the "UserViewModel.Person" members will be disabled.

However ASP.NET MVC doesn't have any concept of validation-groups like WebForms does, so how can I control validation like this?

2 Answers 2

1

I suppose this is more of a binding issue than a validation issue (as validation happens after binding).

I found one solution is to mark the ViewModel with [Bind(Exclude="Person")], and in my Action method to do this:

if( model.PersonViewModelIsNew ) {
    TryUpdateModel( model.Person, "Person" );
}

if( !ModelState.IsValid ) return View( model );

// Update DB here

This approach seems to work for now.

Sign up to request clarification or add additional context in comments.

Comments

0

The MVC Foolproof Validation project adds some good validation rules that cover some situations not covered by validators included with ASP.NET MVC, like the RequiredIfTrue Validation attribute which appears similar to what you need.

Of course you could have written you custom validation rule if you have special requirements, by inheriting the ValidationAttribute class to create your custom validation attribute, you can also optionally provide validation on the client.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.