How can I test the use of DataAnnotations of only part of the fields in the Viewmodel?

I have a Viewmodel that looks like this:

public class Viewmodel
{

  public int Type {get;set} // 0 if typeA, 1 if typeB

  [Required]
  public string AProperty1 {get;set}

  [Required]
  public string AProperty1 {get;set}

  ...

  [Required]
  public string BProperty1 {get;set}

  [Required]
  public string BProperty1 {get;set}
}

There are two forms that receive this view model, and in FormA the user inputs are AProperty1, AProperty2, etc. and BProperty's return as null. Same thing with FormB. The type of the form (FormA or FormB) is assigned to the ViewModel.type field.

So the problem is that in my controller I am checking the ModelState.IsValid property and it will be false in both directions because half of the fields are always zero.

One possible solution would be to override the ModelState.IsValid property in my ModelView so that I can pass this type to it. But as far as I know, there is no way.

Are there any other solutions? (it should preferably be able to use with client-side validation)

+3

Source: https://habr.com/ru/post/1778263/


All Articles