验证复选框mvc

时间:2014-05-24 13:01:50

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

我意识到之前已经问过这个问题,但我仍在努力使用数据注释来验证此复选框。我错过了什么因为它现在没有验证复选框

查看模型

[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)

1 个答案:

答案 0 :(得分:0)

这很好但只是服务器端验证。在Action方法中,执行以下操作:

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