Skip to main content
 首页 » 编程设计

c#之使用 bool 值的数据注释

2024年02月13日1298°冷暖

在下面我有三个不同的类别。

我将如何构造验证以确保每个类别至少选择一个 bool 值?

//残疾

    [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; } 

//年龄段

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

//策略类型

    [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; } 

请您参考如下方法:

您可能需要考虑使用不同的模型。如果您要做的是对每个类别至少执行一个选择,那么最好将它们组合在一起并使用必需的属性。

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

然后像这样在你的模型上有一个属性:

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