簡體   English   中英

數據注釋復選框

[英]Data Annotations Checkbox

有沒有一種方法可以使用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的列表。 我想知道,使用數據注釋選擇了列表中的復選框之一。

視圖模型

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM