简体   繁体   English

ValidationSummary不显示错误

[英]ValidationSummary does not display error

I cannot get a custom error to appear in my ValidationSummary. 我无法在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); 我可以单步执行我的代码,看看行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. 由于其中一个重载接受了Exception ,我假设文本将从我提供的异常中正确提取。 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: 您可能希望将第一个参数更改为false:

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

It specifies whether to exclude property errors. 它指定是否排除属性错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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