Rob L
Rob L

Reputation: 2372

Displaying multiple errors (one per line) in asp-validation-for

ASP.NET Core 3.1

I have the following code in my View:

<span asp-validation-for="NewPassword" class="text-danger"></span>

If I type in a password, such as 'a', I get multiple errors back. I want to display them in that span ONE PER LINE.

In my Controller I have the following:

var descriptions = string.Empty;

foreach (var error in errors)
    descriptions += error.Description + "<br />";

ModelState.AddModelError("NewPassword", descriptions);

But this does not translate the "br" tags and they get displayed as if they were part of one very long single error message.

Note: Adding them one at a time into the ModelState simply overwrites the previous, leaving only the last one displayed.

Instead of "br", i've tried HTMLString.NewLine and Environment.NewLine but none of these work. I could write a loop in my View, but is there a preferred way in ASP.NET Core?

So my question is: How can I put a new line between each description?

Upvotes: 1

Views: 1365

Answers (1)

itminus
itminus

Reputation: 25350

Instead of "br", i've tried HTMLString.NewLine and Environment.NewLine but none of these work.

  1. That's because <br/> will be escaped by default. If you wish, you could use @Html.Raw() to generate the raw content without escaping the dangerous characters. But I don't think it's a good idea: there will be a high risk of XSS if you output a raw string directly.
  2. By default, \r\n won't be displayed in browser. You need a CSS snippet to show a new line.

A much better way is to use the CSS to control the display style: add a style for the validation field in your *.css file:

span.field-validation-error{
  white-space: pre-line;
}

And change the csharp code to use a \n as separator:

foreach (var error in errors)
    descriptions += error.Description + "\n";

Demo :

enter image description here

Upvotes: 4

Related Questions