对于带有.NET的MVC 3中的布尔属性,如何要求值为True?
这就是我的位置,我需要值为True,否则它无效
这就是我的位置,我需要值为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
解决方法
如果有人有兴趣添加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验证属性(“mustbetrue”).
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; });
注意:我将之前的代码基于此答案中使用的代码 – > Perform client side validation for custom attribute
这基本上就是:)
<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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。