我有以下型号:
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属性需要验证器不起作用。即使在动作方法中,ModelState.IsValid也是如此。为什么以及如何做WillAttend是必需的?
答案 0 :(得分:1)
目前,您的required-attribute只检查是否指定了值。由于布尔值为true或false,因此验证永远不会失败。
您可以将布尔值标记为可为空:
cmake -D CMAKE_BUILD_TYPE=RELEASE -D BUILD_PYTHON_SUPPORT=ON
-D WITH_XINE=ON -D WITH_OPENGL=ON -D INSTALL_C_EXAMPLES=ON
-D INSTALL_PYTHON_EXAMPLES=ON -D WITH_TBB=ON -D BUILD_EXAMPLES=ON
-D BUILD_NEW_PYTHON_SUPPORT=ON -D WITH_V4L=ON
-D CMAKE_INSTALL_PREFIX=/home/username/main-env/opencv3.0
-D WITH_GTK = ON -D MATLAB_ROOT_DIR=/home/MATLAB/R2015a ..
或者如果您试图强制他们选中此框,您可以尝试制作自定义验证器,例如in this link。