Data Annotation with Bools

2020-07-29 00:39发布

问题:

Down below I have three different categories.

How would I structure the validation to make sure that at least one boolean gets selected per category?

//Disabilities

    [Display(Name = "Learning Disabilities")]
    public bool LD { get; set; }

    [Display(Name = "Developmental Disabilities")]
    public bool DD { get; set; }

    [Display(Name = "AD/HD")]
    public bool ADHD { get; set; }

    [Display(Name = "Autism")]
    public bool Autism { get; set; }

//Age Group

    [Display(Name = "Child")]
    public bool child { get; set; }

    [Display(Name = "Youth")]
    public bool youth { get; set; }

    [Display(Name = "Adult")]
    public bool adult { get; set; }

//Strategy Type

    [Display(Name = "Academic")]
    public bool academic { get; set; }

    [Display(Name = "Behaviour")]
    public bool behaviour { get; set; }

    [Display(Name = "Communication")]
    public bool communication { get; set; }

    [Display(Name = "Social")]
    public bool social { get; set; }

回答1:

You may want to consider using a different model. If what you are trying to do is enforce at least one selection per category then it may be better to group them together and use a required attribute.

public enum Age
{
  [Display(Name="Child")
  Child,
  [Display(Name="Youth")
  Youth,
  [Display(Name="Adult")
  Adult
}

Then have a property on your model like so:

[Required]
public Age MyAge { get; set; }