Asp.net-Mvc

如何根據多個條件製作所需的屬性?

  • February 21, 2021

我有一對單選按鈕列表(是/否):

Q1.(Y)(N) 
Q2.(Y)(N) 
Q3.(Y)(N) 
Q4.(Y)(N)

我的模型中有一個屬性 public string MedicalExplanation { get; set; }

我的目標是如果任何單選按鈕已設置為 true,則需要進行解釋。

我的第一次嘗試是使用[Required],但它不處理條件。

然後我決定使用像 MVC Foolproof Validation 這樣的第三方工具我這樣使用它: [RequiredIf("Q1", true, ErrorMessage = "You must explain any \"Yes\" answers!")]

現在的問題是,如果選中其他 Q2、Q3、Q4 中的任何一個,我不知道如何使其成為必需。

請指教

在您的 ViewModel 中,創建一個 bool 屬性,如下所示:

public bool IsMedicalExplanationRequired
{
  get
  {
      return Q1 || Q2 || Q3 || Q4;
  }
}

然後,RequiredIf像這樣使用您的屬性:

[RequiredIf("IsMedicalExplanationRequired", true, ErrorMessage = "You must explain any \"Yes\" answers!")]

更新:

如果您的 Q1 - Q4 屬性是 type bool?,只需更改IsMedicalExplanationRequired屬性如下:

public bool IsMedicalExplanationRequired
{
  get
  {
      return Q1.GetValueOrDefault() || Q2.GetValueOrDefault() || Q3.GetValueOrDefault() || Q4.GetValueOrDefault();
  }
}

引用自:https://stackoverflow.com/questions/17795681