如何让基于多个条件所需的属性? [英] How to make a property required based on multiple condition?
问题描述
我有单选按钮对(是/否)的列表:
I have a list of Pair of radio buttons (Yes/No):
Q1.(Y)(N)
Q2.(Y)(N)
Q3.(Y)(N)
Q4.(Y)(N)
和我在我的模型一个属性公共字符串MedicalExplanation {搞定;组; }
and I have one property in my model
public string MedicalExplanation { get; set; }
我的目标是让需要说明是否有任何单选按钮已被设置为true。
My goal is to make Explanation required if any of the radio button has been set to true.
我的第一次尝试是使用 [必需]
,但它不处理的条件。
My first try was to use [Required]
but it does not handle conditions.
然后,我决定使用第三方工具,如MVC验证万无一失
我用它是这样的: [RequiredIf(Q1,真的,的ErrorMessage =你必须解释任何\\是\\答案!)]
Then I decided to use third party tool like MVC Foolproof Validation
I used it like this:
[RequiredIf("Q1", true, ErrorMessage = "You must explain any \"Yes\" answers!")]
现在的问题是,我不知道如何使它如果需要其他任何Q2,Q3的,Q4进行检查。
Now the problem is I don't know how to make it required if any of the other Q2, Q3, Q4 is checked.
请指教
推荐答案
在您的视图模型,创建一个布尔属性格式如下:
In your ViewModel, create a bool propery like this:
public bool IsMedicalExplanationRequired
{
get
{
return Q1 || Q2 || Q3 || Q4;
}
}
然后,使用这样的RequiredIf属性:
Then, use your RequiredIf attribute like this:
[RequiredIf("IsMedicalExplanationRequired", true, ErrorMessage = "You must explain any \"Yes\" answers!")]
更新:
如果您的Q1 - Q4属性类型布尔
的,只是改变像下面的IsMedicalExplanationRequired属性:
If your Q1 - Q4 properties are of type bool?
, just change the IsMedicalExplanationRequired property like below:
public bool IsMedicalExplanationRequired
{
get
{
return Q1.GetValueOrDefault() || Q2.GetValueOrDefault() || Q3.GetValueOrDefault() || Q4.GetValueOrDefault();
}
}
这篇关于如何让基于多个条件所需的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!