这里是一个简单的问题(我认为)。
我有一个表单,底部有一个复选框,用户必须同意其中的条款和条件。如果用户不选中该框,我希望在我的验证摘要中显示一条错误消息以及其他表单错误。
我将其添加到我的 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/