The html tags are displayed as plain text in core mvc razor pages

Sherpa 181 Reputation points

I am working on Asp.Net Core 6.0 MVC Razor pages. On the Login.cshtml page, I want to show the following error message when the user tries to login with in invalid credential: Invalid: <b>User Name</b> and/or <b>Password</b>. The problem is this message is displayed as a text instead of an html with the "User Name" and "Password" in bold. The following is my C# code in Login.cshtml.cs

var invalidLogin = await LockOut(Input.UserUserName, Input.Password);

if (!string.IsNullOrEmpty(invalidLogin))


   invalidLogin = WebUtility.HtmlEncode(invalidLogin);

   ModelState.AddModelError(string.Empty, invalidLogin);

   return Page();


As shown above, I even tried to html encode the message. Still it's displayed as a text, "Invalid: <b>User Name</b> and/or <b>Password</b>." However, since the div in which it is displayed has the class, "text-danger" the color of the text is correctly set as red.

Based on Google search, I have verified that the page source has this line at the top: <!DOCTYPE html>

A set of technologies in the .NET Framework for building web applications and XML web services.
4,292 questions
{count} votes

Accepted answer
  1. Ping Ni-MSFT 2,795 Reputation points Microsoft Vendor

    Hi @Sherpa,

    Firstly, no need encode the error message as HTML(no need use WebUtility.HtmlEncode):

    invalidLogin ="Invalid: <b>User Name</b> and/or <b>Password</b>";
    ModelState.AddModelError(string.Empty, invalidLogin);

    In your Razor Pages .cshtml file, get the ModelState with key name which is empty string here, then use @Html.Raw() to interpret the HTML tags:

    @if (ModelState[""] != null && ModelState[""]?.Errors.Count!=0)
        var error = ModelState[""]?.Errors.First().ErrorMessage;

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce ( 59,131 Reputation points

    the model error collection does not support markup. the string will aways be html encoded before display, which will convert "<b>" to "&lt;b&gt;" which the browser displays as "<b>"