【问题标题】:How to add boolean required attribute in mvc?如何在 mvc 中添加布尔必需属性?
【发布时间】:2014-09-30 13:31:59
【问题描述】:

我有一个模型类,例如:

public class Student
{
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "Enrollment Date")]
    public DateTime EnrollmentDate { get; set; }

    [Required]
    [Display(Name = "Is Active")]
    public bool IsActive { get; set; }

    public virtual ICollection<Enrollment> Enrollments { get; set; }
}

这里我创建了一个Boolean 属性IsActiveRequired 属性,但问题是我的视图没有执行该属性所需的验证?我想将此属性与CheckBox 绑定,并检查是否已检查此CheckBox,如果没有则运行验证。

有什么解决办法吗?

【问题讨论】:

  • 不要认为你可以用必需的来做到这一点。看看这里。这可能会帮助jasonwatmore.com/post/2013/10/16/…
  • Required 属性只是意味着该属性必须有一个值。在布尔值(复选框)的情况下,值 false(或未选中)仍然是有效答案。
  • 我知道它不起作用,因为 unchecked 也是布尔属性的有效值,这就是我正在寻找解决方案的原因。我想知道是否可以在 MVC 中使用默认数据注释?
  • @SonuK 你可以使用自定义验证属性来做到这一点。阅读我添加的链接

标签: asp.net-mvc validation model


【解决方案1】:
[Display(Name = "Is Active")]
[Range(typeof(bool), "true", "true", ErrorMessage="The field Is Active must be checked.")]
public bool IsActive { get; set; }

【讨论】:

  • 谢谢,效果很好。避免创建单独的验证方法的有趣解决方法。
【解决方案2】:

感谢上述解决方案,它让我朝着正确的方向前进,但对我来说效果不佳。我需要将下面的脚本添加到扩展 jquery 验证器的页面中,以获得上述解决方案的工作。如果有人遇到类似问题,考虑分享这个。

<script>
        // extend jquery range validator to work for required checkboxes
        var defaultRangeValidator = $.validator.methods.range;
        $.validator.methods.range = function(value, element, param) {
            if(element.type === 'checkbox') {
                // if it's a checkbox return true if it is checked
                return element.checked;
            } else {
                // otherwise run the default validation function
                return defaultRangeValidator.call(this, value, element, param);
            }
        }
</script>

【讨论】:

    【解决方案3】:

    让我在Sonu K 帖子中添加一点

    如果您对其使用 HTML 验证 (&lt;input type="checkbox" required/&gt;),最终可能会破坏您的 javascript,从而阻止您从模型中提交空的必填字段集

    最后,如果您不想在迁移时将Is Active 添加到数据库中(代码优先),只需添加[NotMapped]

    完整代码

    [NotMapped]
    [Display(Name = "Is Active")]
    [Range(typeof(bool), "true", "true", ErrorMessage="The field Is Active must be checked.")]
    public bool IsActive { get; set; }
    

    因为它在 MVC 中默认设置为 true,尽管它会在浏览器上显示取消选中,因此验证可能无法按您预期的那样工作,这就是为什么您必须添加此 javascript 代码来完善验证。

    <script>
                // extend jquery range validator to work for required checkboxes
                var defaultRangeValidator = $.validator.methods.range;
                $.validator.methods.range = function(value, element, param) {
                    if(element.type === 'checkbox') {
                        // if it's a checkbox return true if it is checked
                        return element.checked;
                    } else {
                        // otherwise run the default validation function
                        return defaultRangeValidator.call(this, value, element, param);
                    }
                }
            </script>
    

    享受编码

    【讨论】:

      【解决方案4】:

      这段代码是最近给我的:

      public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
          {
              public override bool IsValid(object value)
              {
                  return value is bool && (bool)value;
              }
      
      
      
              public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
              {
                  yield return new ModelClientValidationRule
                  {
                      ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                      ValidationType = "booleanrequired"
                  };
              }
          }
      

      然后在定义验证 js 之后添加以下内容:

      $.validator.unobtrusive.adapters.addBool("booleanrequired", "required");
      

      虽然我喜欢使用 Range 的想法,但它很简单,代码更少,上面为您提供了对未来开发人员有意义的适当属性。

      【讨论】:

        【解决方案5】:

        如果您将 IsActive 设置为可为空,那么它应该显示错误消息。

        [Required(ErrorMessage = "Is Active")]
        public bool? IsActive { get; set; }
        

        【讨论】:

          猜你喜欢
          • 2011-02-06
          • 1970-01-01
          • 2013-04-24
          • 1970-01-01
          • 1970-01-01
          • 2012-03-01
          • 2011-12-21
          • 1970-01-01
          • 2013-12-27
          相关资源
          最近更新 更多