简体   繁体   中英

ValidationSummary does not display error

I cannot get a custom error to appear in my ValidationSummary. (Property-level errors display correctly, as expected.)

Controller:

[HttpPost]
public async Task<ActionResult> Contact(ContactViewModel model)
{
    if (ModelState.IsValid)
    {
        try
        {
            Mail mail = new Mail
            {
                ToAddress = "user@example.com",
                Subject = model.Subject,
                Body = model.Message
            };
            if (!string.IsNullOrWhiteSpace(model.Email))
                mail.FromAddress = model.Email;

            await mail.SendAsync();

            return View("ContactConfirm");
        }
        catch (Exception ex)
        {
            ModelState.AddModelError(string.Empty, ex);
        }
    }
    return View(model);
}

View:

@Html.ValidationSummary(true, "", new { @class = "text-danger" })

I can step through my code and see that the line ModelState.AddModelError(string.Empty, ex); is executed, and there is a valid error, but the markup does not render any error message.

NOTE: While nothing is visible on the page, the underlying markup for the validation summary is as follows:

<div class="validation-summary-errors text-danger">
    <ul>
        <li style="display:none"></li>
    </ul>
</div>

Can anyone help me figure out why my error is not displayed?

The problem is here:

catch (Exception ex)
{
    ModelState.AddModelError(string.Empty, ex);
}

Since one of the overloads accepted an Exception , I assumed the text would be correctly extracted from the exception that I provided. But it isn't.

Making the following change causes the error to be displayed correctly in the validation summary.

catch (Exception ex)
{
    ModelState.AddModelError(string.Empty, ex.Message);
}

You probably want to change the first parameter to false:

@Html.ValidationSummary(false, "", new { @class = "text-danger" })

It specifies whether to exclude property errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM