如何在MVC 3 with .NET中为True
属性要求boolean
的值?
这就是我的位置,我需要值为True
,否则它无效
<Required()> _
<DisplayName("Agreement Accepted")> _
Public Property AcceptAgreement As Boolean
如果链接有一天死亡,这是修复
添加此课程
Public Class BooleanMustBeTrueAttribute Inherits ValidationAttribute
Public Overrides Function IsValid(ByVal propertyValue As Object) As Boolean
Return propertyValue IsNot Nothing AndAlso TypeOf propertyValue Is Boolean AndAlso CBool(propertyValue)
End Function
End Class
添加属性
<Required()> _
<DisplayName("Agreement Accepted")> _
<BooleanMustBeTrue(ErrorMessage:="You must agree to the terms and conditions")> _
Public Property AcceptAgreement As Boolean
答案 0 :(得分:4)
如果有人有兴趣添加jquery验证(以便在浏览器和服务器中验证复选框),你应该像这样修改BooleanMustBeTrueAttribute类:
public class BooleanMustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object propertyValue)
{
return propertyValue != null
&& propertyValue is bool
&& (bool)propertyValue;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "mustbetrue"
};
}
}
基本上,该类现在还实现了IClientValidatable,并返回相应的js错误消息和将添加到HTML字段的jquery验证属性(&#34; mustbetrue&#34;)。
现在,为了使jquery验证有效,请将以下js添加到页面中:
jQuery.validator.addMethod('mustBeTrue', function (value) {
return value; // We don't need to check anything else, as we want the value to be true.
}, '');
// and an unobtrusive adapter
jQuery.validator.unobtrusive.adapters.add('mustbetrue', {}, function (options) {
options.rules['mustBeTrue'] = true;
options.messages['mustBeTrue'] = options.message;
});
注意:我将之前的代码基于此答案中使用的代码 - &gt; Perform client side validation for custom attribute
基本上就是这样:)。
请记住,要使之前的js起作用,您必须在页面中包含以下js文件:
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
P.S。当你有它工作时,我实际上建议将代码添加到Scripts文件夹中的js文件,并创建一个包含所有js文件的包。