Nick Harrison
Nick Harrison

Reputation: 937

Define data annotation attributes in one place but use in several view models

I have multiple related ViewModels:

that each include multiple annotation attributes for the password property.

I would like to be able to define these attributes only once.

I tried using a MetadataType attribute to associate each ViewModel with a class that would include all of the associated attributes but since this includes properties that may not be in the individual View Models, I get an error message.

Upvotes: 0

Views: 112

Answers (1)

Rob
Rob

Reputation: 5588

Use inheritance:

public class BasePasswordViewModel
{
     [Required]
     public string Password { get; set; }
     [Required]
     public string ConfirmPassword { get; set; }
}

public class ChangePasswordViewModel: BasePasswordViewModel { //... }

public class ResetPasswordViewModel : BasePasswordViewModel { //... }

public class RegisterViewModel: BasePasswordViewModel { //... }

All of your "shared" properties can go in BasePasswordViewModel and anything that is specific to ChangePasswordViewModel, ResetPasswordViewModel, RegisterViewModel can go in there.

Upvotes: 1

Related Questions