不要为

Don't fire a required validator for

我有以下型号:

public class Model1
{
    [Required(ErrorMessage="E1")]
    public string Name { get; set; }
    [Required(ErrorMessage="E2")]
    [RegularExpression(".+\@.+\..+")]
    public string Email { get; set; }
    [Required(ErrorMessage="E3")]
    public bool WillAttend { get; set; }
}

控制器动作:

    public ActionResult Model1()
    {
        Model1 m = new Model1();
        return View(m);
    }

并查看:

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Model1</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.WillAttend, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.WillAttend)
                    @Html.ValidationMessageFor(model => model.WillAttend, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

问题是 WillAttend 需要验证程序 属性 不起作用。即使在 action 方法中,ModelState.IsValid 也是如此。为什么以及如何做 WillAttend 是必需的?

目前,您的 required-attribute 仅检查是否指定了值。由于布尔值不是真就是假,因此验证永远不会失败。

您可以将布尔值标记为可为空:

public bool? WillAttend { get; set; }

或者如果您试图强制他们选中复选框,您可以尝试制作自定义验证器,例如 in this link