c# - 使用数据注释强制模型的 bool 值为真

标签 c# asp.net asp.net-mvc asp.net-mvc-3

这里是一个简单的问题(我认为)。

我有一个表单,底部有一个复选框,用户必须同意其中的条款和条件。如果用户不选中该框,我希望在我的验证摘要中显示一条错误消息以及其他表单错误。

我将其添加到我的 View 模型中:

[Required]
[Range(1, 1, ErrorMessage = "You must agree to the Terms and Conditions")]
public bool AgreeTerms { get; set; }

但这没有用。

有没有一种简单的方法可以通过数据注释强制一个值为真?

最佳答案

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Checked.Entitites
{
    public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            return value != null && (bool)value == true;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            //return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessage } };
            yield return new ModelClientValidationRule() 
            { 
                ValidationType = "booleanrequired", 
                ErrorMessage = this.ErrorMessageString 
            };
        }
    }
}

关于c# - 使用数据注释强制模型的 bool 值为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6986928/

相关文章:

c# - 我在锁定光标 (Unity) 时遇到问题?

c# - 在 EventTrigger 中为 Storyboard 分配 TargetName

c# - 在 Web 应用程序中选择静态和实例数据访问类的优缺点是什么?

c# - MVC4 .net4 更新前模型刷新?

asp.net-mvc - 如何检查 mvc 5 中的空白用户角色?

c# - 设置 DataGridView 单元格值并添加新行

c# - 捆绑和缩小的问题

c# - 在 _Layout.cshtml 中渲染 JavaScript 文件

javascript - Ajax 调用和 Windows 身份验证无法正常工作

c# - 使用线程池安排方法延迟执行的最佳方法?