2014-02-24 71 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

很好的答案,但這是一個很好的代碼。通過解釋它的作用或工作原理,你可以在這樣的答案中做很多好事 –