Dave S.
Dave S.

Reputation: 183

asp.net core 2.1 displaying HTML in Validation Summary

In normal asp.net MVC if I wanted to include custom html in the Validation summary that was placed there by the controller or other upstream processes and display it in Razor I would simply do something like:

@Html.Raw(HttpUtility.HtmlDecode(Html.ValidationSummary().ToHtmlString()))

in order to get the html decoded. This no longer seems to work in Asp.Net core. How can I achieve the same result in .net core 2.1?

Upvotes: 2

Views: 4794

Answers (1)

John-Luke Laue
John-Luke Laue

Reputation: 3856

In ASP.NET core, you can display a summary of the ModelState errors using asp-validation-summary (see validation documentation)

For example:

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

If you need to access the errors directly and create your own custom html error summary/output, you can use @ViewData.ModelState

For example:

<ul>
    @foreach (var error in ViewData.ModelState.SelectMany(x => x.Value.Errors))
    {
        <li>@error.ErrorMessage</li>
    }
</ul>

If the error message contains raw html, you can use @Html.Raw()

For example:

<ul>
    @foreach (var error in ViewData.ModelState.SelectMany(x => x.Value.Errors))
    {
        <li>@Html.Raw(error.ErrorMessage)</li>
    }
</ul>

Upvotes: 6

Related Questions