【问题标题】:Validation of checkbox mvc验证复选框 mvc
【发布时间】:2014-07-13 18:21:38
【问题描述】:

我意识到之前有人问过这个问题,但我仍在努力使用数据注释验证此复选框。我错过了什么。就像现在一样,该复选框未经过验证

查看模型

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeTrueAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            return value != null && value is bool && (bool)value;
        }

    }
    [Display(Name = "I accept the terms and conditions")]
    [Required]
    [MustBeTrue(ErrorMessage = "Please accept terms and conditions")]
    public bool TermsConditions { get; set; }

Razor 和 html

<div class="editor-label">
    @Html.LabelFor(model => model.TermsConditions)
 </div>
 <div class="editor-field">
     @Html.CheckBoxFor(model => model.TermsConditions, new { id = "chkTermsAndConditions" })
        Yes

  </div>
  @Html.ValidationMessageFor(model => model.TermsConditions)

【问题讨论】:

    标签: asp.net-mvc validation checkbox data-annotations


    【解决方案1】:

    这工作正常,但只是服务器端验证。在您的 Action 方法中,执行以下操作:

    public ActionResult Terms(Terms terms)
    {
        if(!ModelState.IsValid)
        {
            //If checkbox isn't ticked, your code will end up in here
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-02
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 2015-08-29
      • 1970-01-01
      相关资源
      最近更新 更多