简体   繁体   English

数据注释复选框

[英]Data Annotations Checkbox

Is there a way to validate bool checkboxes using Data Annotations in C# MVC? 有没有一种方法可以使用C#MVC中的“数据注释”来验证布尔复选框?

All the examples I have seen for the custom data annotation approach are just validating one checkbox like a Accept Terms box. 我在自定义数据注释方法中看到的所有示例都只是在验证一个复选框,例如“接受条款”框。 I need to validate that at least one checkbox has been selected in a List<> 我需要验证是否在列表<>中至少选中了一个复选框

For Example: 例如:

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

I am storing a list of IsChecked. 我正在存储IsChecked的列表。 I wanted to know rather one of the Checkboxes in the list was selected using Data Annotations. 我想知道,使用数据注释选择了列表中的复选框之一。

ViewModel 视图模型

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

View 视图

@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>

} }

Controller 调节器

[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