【发布时间】:2015-06-28 15:09:32
【问题描述】:
我有以下型号:
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 也是 true。为什么以及如何做 WillAttend 是必需的?
【问题讨论】:
-
你希望Required验证器什么时候触发? Bool 只有两个可能的值(True 和 False),并且都满足 WillAttend 属性具有值的要求。看看问题Boolean value of True for required attribute on MVC .net property。
标签: asp.net-mvc validation requiredfieldvalidator