我正在关注Shawn Wildermuth针对MVC6的优秀Pluralsight教程,并且我仍然坚持要为整个模型显示验证消息。
这是行动:
[HttpPost]
public IActionResult Contact(ContactViewModel model)
{
if (model.Email.Contains("aol.com"))
ModelState.AddModelError("", "We don't support AOL addresses.");
if (ModelState.IsValid)
{
var toAddress = _config["MailSettings:ToAddress"];
_mailService.SendMail(toAddress, model.Email, "Contact Page", model.Message);
}
return View();
}
当我提交表单时,检测到“aol”地址,错误按预期添加到ModelState
,然后IsValid
失败,并返回View()
。< / p>
<h2>Contact Me</h2>
<form method="post">
<span asp-validation-summary="ModelOnly"></span>
<label asp-for="Name">Name</label>
<input asp-for="Name"/>
<span asp-validation-for="Name"></span>
<label asp-for="Email">Email</label>
<input asp-for="Email" type="email"/>
<span asp-validation-for="Email"></span>
<label asp-for="Message">Message</label>
<textarea asp-for="Message" cols="40" rows="4"></textarea>
<span asp-validation-for="Message"></span>
<div>
<input type="submit" value="Send Message"/>
</div>
</form>
可悲的是,DOM检查显示摘要的<span asp-validation-summary="ModelOnly"></span>
仍为空。所有其他表单验证都按预期工作。
建议?