【问题标题】:Boolean value of True for required attribute on MVC .net propertyMVC .net 属性上必需属性的布尔值 True
【发布时间】:2011-10-28 14:45:02
【问题描述】:

如何在带有 .NET 的 MVC 3 中要求 boolean 属性的值为 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

【问题讨论】:

  • 我知道这是旧的,但如果你添加你的解决方案作为答案,我会赞成:)

标签: asp.net-mvc


【解决方案1】:

如果有人有兴趣添加 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字段(“mustbetrue”)的jquery验证属性。

现在,为了让 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 文件的包。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 2012-09-16
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多