模型验证摘要未显示

时间:2016-12-24 05:11:54

标签: jquery asp.net asp.net-mvc validation asp.net-core

我正在关注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>仍为空。所有其他表单验证都按预期工作。

建议?

1 个答案:

答案 0 :(得分:3)

尝试从范围更改

<span asp-validation-summary="All" class="text-danger"></span>

要div

<div asp-validation-summary="All" class="text-danger"></div>

跨度输出:

Span Output

div输出:

div output