Scott Baker
Scott Baker

Reputation: 10443

Model validation Summary not showing up

I'm following along with Shawn Wildermuth's excellent Pluralsight tutorial for MVC6, and I'm stuck on getting a validation message to display for the entire model.

Here's the Action:

[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();
}

and when I submit the form, the "aol" address is detected and the error added to the ModelState as expected, then IsValid fails, and the View() is returned.

<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>

Sadly, DOM inspection reveals that the <span asp-validation-summary="ModelOnly"></span> for the summary remains empty. All the other form validation works as expected.

Suggestions?

Upvotes: 1

Views: 1407

Answers (1)

Sanket
Sanket

Reputation: 20017

Try changing from span

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

To div

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

span output:

Span Output

div output:

div output

Upvotes: 3

Related Questions