2

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?

1 Answer 1

6

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>
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but this doesn't seem to answer my question. I need to know how to display the validation summary with embedded html that has already been placed there by the controller. In the past this was quite easy, but now with .Net Core I can't quite find the path.
@DaveS. See my updated answer. You can still use @Html.Raw(). Does that fully answer your question?
@DaveS. Also, the reason you cannot use @Html.Raw(Html.ValidationSummary()) is because ValidationSummary() returns html encoded output. You could possibly try to WriteTo using a custom encoder (that you would have to write, see stackoverflow.com/a/33679999/3878764), but I think my solution is easier and more maintainable. You could even make a partial view of my solution.
Thanks, this solved the problem of showing decoded HTML content in the errors. Simple and straightforward.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.