在一个位置定义数据注释属性,但在多个视图模型中使用

时间:2021-03-29 16:12:22

I have multiple related ViewModels:

我有多个相关的ViewModel:

  • ChangePasswordViewModel
  • ChangePasswordViewModel
  • ResetPasswordViewModel
  • ResetPasswordViewModel
  • RegisterViewModel
  • RegisterViewModel

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.

我尝试使用MetadataType属性将每个ViewModel与包含所有关联属性的类相关联,但由于这包括可能不在单个View Models中的属性,因此我收到错误消息。

1 个解决方案

#1


1  

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.

所有“共享”属性都可以放在BasePasswordViewModel中,任何特定于ChangePasswordViewModel,ResetPasswordViewModel,RegisterViewModel的内容都可以进入。

#1


1  

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.

所有“共享”属性都可以放在BasePasswordViewModel中,任何特定于ChangePasswordViewModel,ResetPasswordViewModel,RegisterViewModel的内容都可以进入。