【问题标题】:Data Annotations Checkbox数据注释复选框
【发布时间】:2014-02-24 21:12:31
【问题描述】:

有没有办法在 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 的列表。我想知道列表中的一个复选框是使用数据注释选择的。

【问题讨论】:

  • 不完全是数据注释,但你可以试试这个if(ListOfCheckBoxes.Any(x=>x.IsChecked)) {//atleast 1 is checked}
  • 我想目前还没有办法使用数据注释来做到这一点。我已经使用了你上面的方法。我只是希望有一个数据注释替代方案。

标签: c# asp.net asp.net-mvc data-annotations


【解决方案1】:

视图模型

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

【讨论】:

  • 不错的答案,但这是一段很好的代码。通过解释它的作用或工作原理,您可以在此类答案中做很多好事
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-11
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-08
  • 2016-06-20
相关资源
最近更新 更多