2014-05-24 66 views
0

我意識到這個問題之前已經被問過了,但我仍然在努力驗證使用數據註釋的複選框。我錯過了什麼。由於這是現在的複選框未通過驗證驗證複選框mvc

視圖模型

[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; } 

剃刀和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) 

回答

0

這是工作正常,但只有服務器端驗證。在您的操作方法中,執行以下操作:

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