不需要必需属性的bool属性

时间:2013-02-20 23:39:12

标签: asp.net-mvc asp.net-mvc-3

有一个简单的ViewModel,它有三个属性,如:

public bool RememberMe { get; set; }

在我看来,我有一个简单的@Html.CheckBoxFor(p => p.RememberMe) 我正在使用Html.EnableClientValidation();

启用客户端验证

为什么将其设置为必填字段?

2 个答案:

答案 0 :(得分:11)

尝试一个可空的布尔。

public bool? RememberMe { get; set; }

使用引用类型时,会应用许多默认验证规则。如果引用类型不可为空,则默认情况下它是必需的。最好的例子是,如果您使用文本框来显示某些属性(不是您在网站中要做的事情,而是出于测试目的):

型号:

public bool? MyBool { get; set; }
public int MyInt { get; set; }

查看:

 @Html.TextBoxFor(p => p.MyBool)
 @Html.TextBoxFor(p => p.MyInt)

您可以从视图来源中看到页面上发生了什么:

<input id="MyNullBool" name="MyNullBool" type="text" value="">
<input data-val="true" data-val-required="The MyBool field is required." id="MyBool" name="MyBool" type="text" value="False">
<input data-val="true" data-val-number="The field MyInt must be a number." data-val-required="The MyInt field is required." id="MyInt" name="MyInt" type="text" value="0">

可空的bool没有验证属性,而bool有data-val-required标记。 int具有data-val-required标记和data-val-number属性

当然,在一个复选框上,这一切都非常冗余,因为它只能被检查(真实)或不被检查(错误),因此所需的标签用处不大。

答案 1 :(得分:-2)

@Html.CheckBoxFor(c => c.TermsAndConditions, new { required = "required" })
@Html.ValidationMessageFor(c => c.TermsAndConditions, "you must agree to terms and conditions of Service.)"
相关问题