加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – MVC .net属性上必需属性的布尔值True

发布时间:2020-12-16 10:01:18 所属栏目:asp.Net 来源:网络整理
导读:对于带有.NET的MVC 3中的布尔属性,如何要求值为True? 这就是我的位置,我需要值为True,否则它无效 Required() _DisplayName("Agreement Accepted") _Public Property AcceptAgreement As Boolean 这是修复,以防链接有一天死亡 添加此课程 Public Class Boole
对于带有.NET的MVC 3中的布尔属性,如何要求值为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验证起作用,将以下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;
});

注意:我将之前的代码基于此答案中使用的代码 – > 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>

附:当你有它工作时,我实际上建议将代码添加到Scripts文件夹中的js文件,并创建一个包含所有js文件的包.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读