我正在使用MVC5,并且在验证摘要部分和每个控件的各个验证消息中都显示对象的验证错误。
尽管我们在网络配置中启用了IT并包含了js文件,但我们暂时不考虑客户端验证。
如果将无效的模型传递给已有验证摘要(将excludePropertyErrors设置为false)的视图,并且每个控件都有一个@ Html.ValidationMessageFor(model => model.Summary,&#34) ;",new {@class =" text-danger"}),显示所有这些在页面加载时显示对象中的验证错误。
我们检查了对象并且framwork知道它是invlaid(ModelState.IsValid肯定是假的)并且errors集合包含几个验证错误 (System.Data.Entity.Validation.DbValidationError)但在页面加载时,它们都不会出现在ValidationSummary或ValidationMessage中的各个控件上。
目前我通过context.Entry(prop)手动验证错误.GetValidationResult()。ValidationErrors.ToList();并将其传递给Viewbag并在视图中迭代它们以显示它们。看起来很疯狂!
P.S。主视图由几个部分视图组成,其中控件是,Vaidationsummary在Main包含视图中。
public async Task<ActionResult> GetProduct(id)
{
var product= await context.Products.FindAsync(id);
return View(product);
}
正如我所提到的,任何地方都没有任何确认信息。如果我们关闭客户端验证,则输入控件html为
<input class="form-control text-box single-line valid" id="Price" name="Price" style="font-weight:bold" type="text" value="" aria-invalid="false">
正如您所看到的,该值为空但是它表示它是有效的,即使该字段是通过DataAnnotations标记的必填字段且模型为INVALID并且包含需要Price字段的验证错误!
以下是代码:
<div class="form-group">
@Html.LabelFor(m => m.Price, new { @class = "col-sm-3 control-label" })
<div class="col-sm-5">
@Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control", style = "font-weight:bold" } })
@Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })
</div>
</div>
这是生成的html,启用了客户端验证:
<input class="form-control text-box single-line" data-val="true" data-val-number="The field Price must be a number." data-val-required="The Price field is required." id="Price" name="Price" style="font-weight:bold" type="text" value="">
非常感谢任何帮助。