Reputation: 67203
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 = "[email protected]",
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?
Upvotes: 1
Views: 1844
Reputation: 67203
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);
}
Upvotes: 3
Reputation: 951
You probably want to change the first parameter to false:
@Html.ValidationSummary(false, "", new { @class = "text-danger" })
It specifies whether to exclude property errors.
Upvotes: 0