2014-02-24 40 views
1

有没有一种方法来验证在C#MVC中使用数据注释的布尔复选框?数据注释复选框

我看到的自定义数据注释方法的所有例子只是验证一个复选框,如接受条款框。我需要验证至少一个复选框已在列表<>

被选自例如:

public class QuestionOptionViewModel 
{ 
    public int? Id { get; set; } 

    public string Text { get; set; } 

    public string QuestionType { get; set; } 

    [RequiredIf("QuestionType", "text", ErrorMessage = "Required Field")] 
    public string Value { get; set; } 

    [RequiredIf("QuestionType", "checkbox", ErrorMessage = "Required Field")] 
    public bool IsChecked { get; set; } 
} 

我存储器isChecked的列表。我想知道列表中的其中一个复选框是使用数据注释选择的。

+0

不完全数据注解,但你可以试试这个 '如果(ListOfCheckBoxes.Any(X => x.IsChecked)){// ATLEAST 1检查}' – neo112

+0

我想作为目前也没办法使用数据注解来做到这一点。我已经使用了上面的方法。我只是希望有一个数据注释的选择。 – allencoded

回答

0

视图模型

public class VisitorAgreementTermViewModel 
{ 
    [Required] 
    [Display(Name = "Message Accept.")] 
    //[Range(typeof(bool), "true", "true", ErrorMessage = "Error Message Text.")] 
    [RegularExpression("True", ErrorMessage = "Error Message Text.")] 
    public bool Agreement { get; set; } 
} 

查看

@using (Ajax.BeginForm("AgreementTerms", "Visitors", new AjaxOptions() 
{ 
    HttpMethod = "POST", 
    UpdateTargetId = "document-body", 
    InsertionMode = InsertionMode.Replace, 
    LoadingElementId = "document-loading", 
    OnBegin = "ClearBody('document-body')" 
})) 
{ 
    @Html.AntiForgeryToken() 

<div class="row"> 
    <div class="form-group m-b-xl col-md-offset-1"> 
     <label class="checkbox-inline"> 
      @Html.CheckBoxFor(model => model.Agreement) 
      @Html.LabelFor(model => model.Agreement) 
      <br /> 
      @Html.ValidationMessageFor(model => model.Agreement, "", new { @class = "text-danger" }) 
      @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
     </label> 
    </div> 
    <div class="col-sm-2 col-sm-offset-9"> 
     <button type="submit" class="btn btn-success"><span class="fa fa-fw fa-arrow-right"></span>&nbsp;&nbsp;Continue</button> 
    </div> 
</div> 

}

控制器

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult AgreementTerms(AgreementTermViewModel aterms) 
{ 
    if (ModelState.IsValid) 
      return PartialView("_PreRegistration"); 

    return PartialView("_AgreementTerms", aterms); 
} 
+1

很好的答案,但这是一个很好的代码。通过解释它的作用或工作原理,你可以在这样的答案中做很多好事 –